水平条形图,y轴为日期

时间:2013-09-27 15:26:18

标签: python matplotlib

我想了解如何在聚类水平条形图中绘制每个日期的均值,最大值,最小值的示例。

dates = [datetime.datetime(2011, 1, 2, 0, 0, 25, 135000),
datetime.datetime(2011, 2, 2, 0, 0, 57, 386000), 
datetime.datetime(2011, 3, 2, 0, 0, 59, 579000), 
datetime.datetime(2011, 4, 2, 0, 0, 27, 676000), 
datetime.datetime(2011, 5, 2, 0, 0, 25, 135000), 
datetime.datetime(2011, 6, 2, 0, 0, 26, 414000), 
datetime.datetime(2011, 7, 2, 0, 0, 28, 145000), 
datetime.datetime(2011, 8, 2, 0, 0, 26, 432000), 
datetime.datetime(2011, 9, 2, 0, 0, 27, 301000), 
datetime.datetime(2011, 10, 2, 0, 0, 27, 643000), 
datetime.datetime(2011, 11, 2, 0, 0, 27, 673000), 
datetime.datetime(2011, 12, 2, 0, 0, 28, 294000)]


mean = [-10.246537396121893, 1.3039215686274515, 1.007462686567164,
-0.12771084337349403, -0.1932367149758454, -0.3196125907990315, 
-0.04128440366972498, -0.19950738916256117, -1.6319018404907975, 
-1.1532258064516134, -1.666666666666668, -2.3958333333333326]


max = [-8.0, 19.0, 11.0, 6.0, 6.0, 6.0, 6.0, 6.0, 2.0, 2.0, 2.0, 2.0]


min = [-12.0, -7.0, -6.0, -6.0, -6.0, -6.0, -6.0, -6.0, -6.0, -6.0, -7.0, -7.0]

我尝试使用barh方法没有成功使日期显示y轴侧。

dates = [datetime.datetime(2011, 1, 2, 0, 0, 25, 135000),
    datetime.datetime(2011, 2, 2, 0, 0, 57, 386000), 
    datetime.datetime(2011, 3, 2, 0, 0, 59, 579000), 
    datetime.datetime(2011, 4, 2, 0, 0, 27, 676000), 
    datetime.datetime(2011, 5, 2, 0, 0, 25, 135000), 
    datetime.datetime(2011, 6, 2, 0, 0, 26, 414000), 
    datetime.datetime(2011, 7, 2, 0, 0, 28, 145000), 
    datetime.datetime(2011, 8, 2, 0, 0, 26, 432000), 
    datetime.datetime(2011, 9, 2, 0, 0, 27, 301000), 
    datetime.datetime(2011, 10, 2, 0, 0, 27, 643000), 
    datetime.datetime(2011, 11, 2, 0, 0, 27, 673000), 
    datetime.datetime(2011, 12, 2, 0, 0, 28, 294000)]

data_values = [
[-10.246537396121893, 1.3039215686274515, 1.007462686567164,
-0.12771084337349403, -0.1932367149758454, -0.3196125907990315, 
-0.04128440366972498, -0.19950738916256117, -1.6319018404907975, 
-1.1532258064516134, -1.666666666666668, -2.3958333333333326], #mean
[-8.0, 19.0, 11.0, 6.0, 6.0, 6.0, 6.0, 6.0, 2.0, 2.0, 2.0, 2.0], #max
[-12.0, -7.0, -6.0, -6.0, -6.0, -6.0, -6.0, -6.0, -6.0, -6.0, -7.0, -7.0]]#min

width = 0.35
ind = arange(len(dates))

for i in range(len(data_values)):
    plt.barh(ind + width * i, data_values[i], width)

如何在y轴侧显示与日期对应的每个平均值,最大值,最小值栏的日期?谢谢你的帮助。

1 个答案:

答案 0 :(得分:4)

这是你想要的效果吗?

horizontal bar

关键是使用matplotlib.dates模块正确设置日期格式:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
datenum = matplotlib.dates.date2num(dates)

for i in range(-1,len(data_values)-1):
    ax.barh(datenum + i*5., data_values[i], height=5.)
ax.yaxis.set_major_formatter(matplotlib.dates.DateFormatter('%m/%d'))

plt.show()