matplotlib居中条形图与日期

时间:2012-04-23 11:37:34

标签: python datetime matplotlib

要获得x轴为日期的条形,我正在做这样的事情:

import numpy as np
import matplotlib.pyplot as plt
import datetime

x = [datetime.datetime(2010, 12, 1, 0, 0),
    datetime.datetime(2011, 1, 1, 0, 0),
    datetime.datetime(2011, 5, 1, 1, 0)]
y = [4, 9, 2]

ax = plt.subplot(111)
barWidth=20
ax.bar(x, y, width=barWidth)
ax.xaxis_date()

plt.show()

enter image description here

但是,图不以x为中心。如果以前使用过ax.bar(x-barWidth / 2.,y,width = barWidth)来获取以x为中心的条形。当x轴值是日期时,有没有办法获得相同的效果?

1 个答案:

答案 0 :(得分:32)

我认为align='center'方法需要bar个关键字。

对您的示例进行细微更改:

import numpy as np
import matplotlib.pyplot as plt
import datetime

x = [datetime.datetime(2010, 12, 1, 0, 0),
    datetime.datetime(2011, 1, 1, 0, 0),
    datetime.datetime(2011, 5, 1, 1, 0)]
y = [4, 9, 2]

ax = plt.subplot(111)
barWidth=20
ax.bar(x, y, width=barWidth, align='center') #< added align keyword
ax.xaxis_date()

plt.savefig('baralign.png')
plt.show()

导致下图:

enter image description here

如果你知道在哪里看,这是一个非常直截了当的答案。 matplotlib有大量文档,开发人员提供a detailed description of the keyword arguments每种绘图方法。