如何在条形图中为y轴和第一条柱子之间留出间隙
我有一段画柱状图的代码,如下所示。当你运行这段代码时,会得到4根柱子,其中第一根柱子是紧贴着y轴的。请问有没有办法在y轴和第一根柱子之间留一些空隙呢?
def plot_graph1():
xvals = range(4)
xnames=["one","two","three","four"]
yvals = [10,30,40,20]
width = 0.25
yinterval = 10
figure = plt.figure()
plt.grid(True)
plt.xlabel('x vals')
plt.ylabel('y vals')
plt.bar(xvals, yvals, width=width)
plt.xticks([ x+(width/2) for x in xvals],[x for x in xnames])
plt.yticks(range(0,max(yvals),yinterval))
figure.savefig("barchart.png",format="png")
plt.show()
if __name__=='__main__':
plot_graph1()
运行后的效果如下:
1 个回答
16
使用 plt.margins
和 plt.ylim(ymin=0)
是最简单的方法。margins
的作用类似于 axis('tight')
,但它会留出一定比例的“边距”,而不是直接缩放到数据的确切范围。
另外,plt.bar
还有一个 align="center"
的选项,可以让你的例子更简单一些。
下面是你上面例子的一个稍微简化的版本:
import matplotlib.pyplot as plt
def plot_graph1():
xvals = range(4)
xnames=["one","two","three","four"]
yvals = [10,30,40,20]
width = 0.25
yinterval = 10
figure = plt.figure()
plt.grid(True)
plt.xlabel('x vals')
plt.ylabel('y vals')
plt.bar(xvals, yvals, width=width, align='center')
plt.xticks(xvals, xnames)
plt.yticks(range(0,max(yvals),yinterval))
plt.xlim([min(xvals) - 0.5, max(xvals) + 0.5])
figure.savefig("barchart.png",format="png")
plt.show()
if __name__=='__main__':
plot_graph1()