我试图根据时间绘制用电量。我正在使用这个脚本:
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
timelist = []
valuelist = []
# Logic that populates timelist and valuelist
timeaxis = np.array(timelist)
valueaxis = np.array(valuelist)
plt.plot(timeaxis, valueaxis, 'r-')
plt.savefig('elec_use.png', bbox_inches='tight')
plt.show()
我尝试通过添加xticks
来旋转标签,如下所示:
plt.xticks(timeaxis, rotation=90)
我该如何解决这个问题?我尝试添加plt.gcf().subplots_adjust(bottom=0.25)
,但这并没有修复标签,它只是将房地产增加到图表的底部。我希望x轴标签说Jun 02 2016
或简称Jun 02
。我不介意图表是宽的。提前感谢您的帮助。
答案 0 :(得分:1)
您可以使用gcf().autofmt_xdate很好地格式化x轴。对于日期字符串格式,您可以使用matplotlib.dates.DateFormatter
。它将如下所示:
所以你的代码将是这样的:
fig, ax = plt.subplots(1)
timelist = []
valuelist = []
# Logic that populates timelist and valuelist
timeaxis = np.array(timelist)
valueaxis = np.array(valuelist)
ax.plot(timeaxis, valueaxis, 'r-')
# rotate and align the tick labels so they look better
fig.autofmt_xdate()
# use a more precise date string for the x axis locations in the
# toolbar
import matplotlib.dates as mdates
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
plt.savefig('elec_use.png', bbox_inches='tight')
plt.show()