在matplotlib中绘制多个条形图

时间:2017-07-04 12:37:10

标签: python matplotlib

def plotbars(hists, bins, labels, filename):
    plt.figure()
    center = (bins[:-1] + bins[1:]) / 2
    width = 0.7 * (bins[1] - bins[0])
    for hist in hists:
        plt.bar(center, hist, align='center', width=width)
    plt.legend(labels)
    plt.savefig(filename)

如果我绘制像plotbars([hist1, hist2], bins, ['hist1', 'hist2'], 'histo.png')这样的直方图,则会将直方图绘制在彼此之上。我希望直方图的条形相邻。每个的bin宽度相等。

1 个答案:

答案 0 :(得分:1)

尝试使用plt.hist而不是plt.bar。

hist1=[x for x in range(0,10)]*10
hist2= [x for x in range(0,10)]*2
plt.hist([hist1,hist2],bins = 10)

产生此图像:

enter image description here

这是您希望看到图表的方式吗?

更新

可以使用以下方法正确格式化x轴。

bin_list = [x for x in range(0,11) ]
plt.hist([hist1,hist2], bins=bin_list ,align='left')

产生适当间隔的x轴。出于某种原因,似乎必须将箱子设置为适当间隔x值的列表。

enter image description here

https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks

如需进一步调整,您可以尝试使用plt.xticks()。

相关问题