如何在柱状图中在y轴和第一根柱子之间留出间隙

13
我有一个条形图的代码片段如下...当你运行它时,你会得到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()

输出如下:

barchart as produced by above code

1个回答

16

使用plt.marginsplt.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()

enter image description here


我的初始图看起来像你的答案中的那个,你知道我怎样才能重现问题中那个棒棒一直粘在y轴上的图吗? - weefwefwqg3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接