折线图中的中心x轴标签

折线图中的中心x轴标签,第1张

折线图中的中心x轴标签

按照DavidG发布的主题中的建议使用次要刻度线应该可以工作。以下是我已针对您的特定问题进行了调整的MWE,它迫使主要价格变动出现在每个月的第一天,并使用次要价格变动将标签放置在主要价格变动之间:

import matplotlib as mplimport matplotlib.pyplot as pltimport numpy as npimport datetime# Generate some data for example :yr = 2014fig, ax = plt.subplots()x0 = datetime.datetime(yr, 1, 1)x = np.array([x0 + datetime.timedelta(days=i) for i in range(365)])y1 = np.sin(2*np.pi*np.arange(365)/365) + np.random.rand(365)/5y2 = np.sin(2*np.pi*np.arange(365)/365) + np.random.rand(365)/5 - 1# Draw high and low temperatures lines :ax.plot(x, y1, color='#c83c34')ax.plot(x, y2, color='#28659c')ax.fill_between(x, y2, y1, facecolor='#daecfd', alpha=0.5)# Force the major ticks position on the first of each month and hide labels:xticks = [datetime.datetime(yr, i+1, 1) for i in range(12)]xticks.append(datetime.datetime(yr+1, 1, 1))ax.set_xticks(xticks)ax.tick_params(axis='both', direction='out', top=False, right=False)ax.axis([xticks[0], xticks[-1], -2.5, 1.5])ax.set_xticklabels([])# CODE GOES HERE TO CENTER X-AXIS LABELS...labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']mticks = ax.get_xticks()ax.set_xticks((mticks[:-1]+mticks[1:])/2, minor=True)ax.tick_params(axis='x', which='minor', length=0)ax.set_xticklabels(labels, minor=True)fig.tight_layout()plt.show()

结果是:



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5640230.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存