如何禁用matplotlib柱状图的自动缩放?
我有一组数据,里面包含了一月份每一天的数值:
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
值。但是我得到的图表是这样的:
为什么图表上只显示了4个数值?我该如何显示所有31个数值呢?
1 个回答
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()
注意:这个matplotlib论坛的帖子也描述了类似的问题。
(我只能猜测你的x值是从哪里来的,但原理是可以看得出来的)