matplotlib中以日期为x轴的最简单直方图

时间:2018-07-13 09:09:04

标签: python matplotlib

我一直在尝试正确地显示一个简单的直方图,其中日期作为x轴,整数作为y轴。下面的示例碰巧是一个子图(2个y轴,1个共享的x轴),但问题不存在,而是历史记录本身。

import datetime
import matplotlib
matplotlib.use('agg')   # server no need to display graphics
import matplotlib.pyplot as plt

# x-axis is 3 consecutive dates (days)
now = datetime.datetime.now().date()
x = [now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)]

# y1-axis is 3 numbers
y1 = [10, 0, 3]
y2 = [8, 0, 3]

fig, axarr = plt.subplots(2, sharex=True)
bins = range(1, len(x) + 1)
axarr[1].hist(y1, bins=len(x), edgecolor="k")
axarr[1].set_xticks(bins)
axarr[1].set_xticklabels(x)
axarr[1].set_yticks(range(0, max(y1) + 1))

# axarr[0] ommitted for simplicity

plt.savefig('a.png', bbox_inches='tight')

但是我得到的图像是...

enter image description here

2 个答案:

答案 0 :(得分:0)

如果要在直方图的x轴上显示日期,则必须将这些日期作为hist的参数。

now = datetime.datetime.now().date()
x = [now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)]

axarr[1].hist(x, edgecolor="k")

enter image description here

答案 1 :(得分:0)

您可能想要一个bar图。

import datetime
import matplotlib
matplotlib.use('agg')   # server no need to display graphics
import matplotlib.pyplot as plt

# x-axis is 3 consecutive dates (days)
now = datetime.datetime.now().date()
x = [now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)]

# y1-axis is 3 numbers
y1 = [10, 0, 3]
y2 = [8, 0, 3]

fig, axarr = plt.subplots(2, sharex=True)
bins = range(1, len(x) + 1)
axarr[1].bar(x, y1, edgecolor="k")
axarr[1].set_xticks(x)
axarr[1].set_xticklabels(x)

plt.savefig('a.png', bbox_inches='tight')

enter image description here