我有一个条形图代码片段如下所示。当你运行它时,你会得到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()
输出如下
任何帮助表示赞赏
感谢
标记
答案 0 :(得分:15)
在您的具体情况下,最简单的方法是使用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()