Matplotlib如何设置x轴以对应于一周中的几天?

时间:2017-04-27 12:36:45

标签: python-3.x matplotlib graph

我有一个图表,用于绘制一周percent of scores over 100 by hour

的分数

我正在使用简单的增量器来绘制x轴

percent = []
count = 0
time = []
for x, y in zip(counts100, counts):
    percent.append(float(x/y))
    time.append(count)
    count += 1


plt.xlabel('weekday')
plt.ylabel('% score over 100')
plt.plot( time, percent )
plt.gcf().autofmt_xdate()
plt.show()

这会正确显示数据,但x轴只读取数字。

如何将此转换为工作日?感谢

编辑: 我找到了这个答案here,我试图让它适应我的问题,它几乎可以工作,但我一直都会遇到奇怪的错误

 File "/usr/local/lib/python3.5/dist-packages/matplotlib/dates.py", line 401, in num2date
 return _from_ordinalf(x, tz)
 File "/usr/local/lib/python3.5/dist-packages/matplotlib/dates.py", line 254, in _from_ordinalf
    dt = datetime.datetime.fromordinal(ix).replace(tzinfo=UTC)
ValueError: ordinal must be >= 1

1 个答案:

答案 0 :(得分:0)

我找到了解决方案here。在我的问题编辑中,我没有改变沿X轴绘制的值。

percent = []
count = 0
time = []
for x, y, z in zip(counts100, counts, hour):
    percent.append(float(x/y))
    time.append(count)
    count += 1
    print("the percent is : {:.4f}  for hour {}".format(float(x/y), z))



times = pd.date_range('2017-10-06 00:00', periods=count, freq='1H', tz = 'UTC')

fig, ax = plt.subplots(1)
fig.autofmt_xdate()

plt.xlabel('weekday')
plt.ylabel('% score over 100')
plt.plot( times, percent )
xfmt = mdates.DateFormatter('%d %H:%M')
ax.xaxis.set_major_formatter(xfmt)

plt.show()

enter image description here