Skip to main content
 首页 » 编程设计

python之在同一图上绘制多个直方图的问题

2025年05月04日8think

我需要在同一个图上绘制多个直方图。我喜欢以下代码生成的显示:

import random 
import numpy 
from matplotlib import pyplot 
 
x = [random.gauss(3,1) for _ in range(400)] 
y = [random.gauss(4,2) for _ in range(400)] 
 
bins = numpy.linspace(-10, 10, 100) 
 
pyplot.hist(x, bins, alpha=0.5) 
pyplot.hist(y, bins, alpha=0.5) 
pyplot.show() 

此页面上提到了此代码:Plot two histograms at the same time with matplotlib 基本上我在绘制相同类型的直方图时遇到了问题,但对于看起来像的数据:

y1=[20,33,54,34,22] 
x1=[0,2,4,6,8] 
y2=[28,31,59,14,12] 
x2=[0,2,4,6,8] 

使用上述代码我无法让 y 轴超过 2.0 奇怪但我一定是犯了一个愚蠢的错误。

谢谢。

请您参考如下方法:

可能您正在寻找这个:

 pyplot.bar(x2,y2, color='b', width=2, alpha=0.5) 
 pyplot.bar(x1,y1, color='r', width=2, alpha=0.5) 
 pyplot.show()