如何在条形图中的 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()
输出如下
I have a barchart code snippet as below..When you run this,you get 4 bars ,the first of which lies against the y axis.Is it possible to put some gap between y axis and the first bar?
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()
The output is as below
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的使用
plt.margins
和plt.ylim(ymin=0)
。margins
的作用类似于axis('tight')
,但保留指定的“填充”百分比,而不是缩放到数据的精确限制。此外,
plt.bar
有一个align="center"
选项,可以在一定程度上简化您的示例。这是上面示例的稍微简化的版本:
It's easiest to use
plt.margins
andplt.ylim(ymin=0)
.margins
will act likeaxis('tight')
, but leave the specified percentage of "padding", instead of scaling to the exact limits of the data.Also,
plt.bar
has analign="center"
option that simplifies your example somewhat.Here's a slightly simplified version of your example above: