如何在垂直条形图matplotlib中放置y轴和第一个条之间的间隙

时间:2011-07-10 16:57:03

标签: python matplotlib bar-chart

我有一个条形图代码片段如下所示。当你运行它时,你会得到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 个答案:

答案 0 :(得分:15)

在您的具体情况下,最简单的方法是使用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