首页 > 解决方案 > Matplotlib x 轴日期到日期时间格式

问题描述

我有一个 matplotlib 图,显示了几年数据中每天的最大和最小温度。我当前的 xaxis 是这个数据的索引,所以 365 个数据点。我想将其更改为月份显示在 x 轴而不是索引上的位置。

我有什么方法可以做到这一点?

以下是我的 jupyter 笔记本绘图单元中的代码。"""

plt.figure(figsize=(16,10))
plt.xlabel('Day of Year', fontsize=20)
plt.ylabel('Temperature (℃)', fontsize=20)


plt.title('Ten Year Record (2005-2014) Near Ann Arbor, Michigan', fontsize=25) 
plt.plot(max_04to15.values, c = 'red', label ='Record High')
plt.plot(min_04to15.values, c = 'blue', label ='Record Low')
#plt.plot(mean_04to15.values, c = 'black', label = 'Average Temp')

plt.scatter(break_max.index.tolist(), break_max['Data_Value_y'].values, marker = "^", c = 'black', label = "Broken High in 2015")
plt.scatter(break_min.index.tolist(), break_min['Data_Value_y'].values, marker = "v", c = 'orange', label = "Broken Low in 2015")


plt.gca().fill_between(range(len(max_04to15)), 
                       np.array(max_04to15.values.reshape(len(min_04to15.values),)), 
                       np.array(min_04to15.values.reshape(len(min_04to15.values),)), 
                       facecolor='#2F99B4', 
                       alpha=0.25)

plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.legend(loc = 'best', fontsize=18, frameon = False)
plt.show()

"""

标签: pythondatetimematplotlib

解决方案


一种方法是您可以使用 numpy 创建日期时间数组:

ax.fill_between(np.arange('2019-01-01', '2020-01-01', dtype='datetime64[D]'), 
                       upper, lower, facecolor='#2F99B4', alpha=0.25)

推荐阅读