如何在matplotlib条形图中禁用自动缩放?

时间:2014-03-07 12:41:05

标签: python charts matplotlib

我有一个数据,其中包含 1月 每天的值:

self.y_data:  [0, 0, -4, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

matplotlib条形图使用此self.y_data为每天设置y值。但我得到以下图表:

enter image description here

为什么图中只显示4个值?如何显示所有31个值?

1 个答案:

答案 0 :(得分:2)

似乎x轴范围未设置为包括数据为零的点。一种解决方法是根据数据显式设置x限制。

import matplotlib.pyplot as plt 

y  = [0, 0, -4, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0]
x = xrange(len(y))

fig, ax = plt.subplots(1, 2)
# show with default limits
h0 = ax[0].bar(x, y)
# same data, but explicitly set x range
h1 = ax[1].bar(x, y)
ax[1].set_xlim(x[0], x[-1]+1)

plt.show()

bar charts with different ranges

注意:此matplotlib forum post也描述了类似的问题。

(我不得不猜测你的x值来自哪里,但原理显示了)