在matplotlib中绘制多个条形图

2024-09-30 22:16:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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'),那么柱状图会相互叠加。我希望柱状图的条形图是相邻的。每个箱子的宽度相等。在


Tags: forlabelsdefpltfilenamewidthhistfigure
1条回答
网友
1楼 · 发布于 2024-09-30 22:16:11

尝试使用plt.hist公司而不是板条. 在

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轴可以使用以下方法正确格式化。在

^{pr2}$

产生适当间隔的x轴。出于某些原因,似乎必须将存储箱设置为一个列表,以确保x值的适当间距。在

enter image description here

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

为了进一步调整,你可以试着玩plt.xticks公司(). 在

相关问题 更多 >