我用一个文件中的数据创建了一个直方图,没有问题。现在我想在同一直方图中叠加来自另一个文件的数据,所以我这样做
n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)
但问题是,对于每个区间,只有最高值的条出现,而另一个条被隐藏。我想知道如何用不同的颜色同时绘制两个直方图。
我用一个文件中的数据创建了一个直方图,没有问题。现在我想在同一直方图中叠加来自另一个文件的数据,所以我这样做
n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)
但问题是,对于每个区间,只有最高值的条出现,而另一个条被隐藏。我想知道如何用不同的颜色同时绘制两个直方图。
当前回答
你应该使用hist返回值中的bin:
import numpy as np
import matplotlib.pyplot as plt
foo = np.random.normal(loc=1, size=100) # a normal distribution
bar = np.random.normal(loc=-1, size=10000) # a normal distribution
_, bins, _ = plt.hist(foo, bins=50, range=[-6, 6], normed=True)
_ = plt.hist(bar, bins=bins, alpha=0.5, normed=True)
其他回答
听起来你可能只需要一个柱状图:
http://matplotlib.sourceforge.net/examples/pylab_examples/bar_stacked.html http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html
或者,您可以使用子情节。
作为Gustavo Bezerra回答的补充:
如果你想要每个直方图被归一化(对mpl<=2.1进行归一化,对mpl>=3.1进行密度归一化),你不能只使用归一化/密度=True,你需要为每个值设置权重:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.normal(1, 2, 5000)
y = np.random.normal(-1, 3, 2000)
x_w = np.empty(x.shape)
x_w.fill(1/x.shape[0])
y_w = np.empty(y.shape)
y_w.fill(1/y.shape[0])
bins = np.linspace(-10, 10, 30)
plt.hist([x, y], bins, weights=[x_w, y_w], label=['x', 'y'])
plt.legend(loc='upper right')
plt.show()
作为比较,完全相同的x和y向量,默认权重和密度=True:
这里有一个工作示例:
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, label='x')
pyplot.hist(y, bins, alpha=0.5, label='y')
pyplot.legend(loc='upper right')
pyplot.show()
你应该使用hist返回值中的bin:
import numpy as np
import matplotlib.pyplot as plt
foo = np.random.normal(loc=1, size=100) # a normal distribution
bar = np.random.normal(loc=-1, size=10000) # a normal distribution
_, bins, _ = plt.hist(foo, bins=50, range=[-6, 6], normed=True)
_ = plt.hist(bar, bins=bins, alpha=0.5, normed=True)
下面是一个简单的方法来绘制两个直方图,当数据大小不同时,它们的柱状图并排在同一个图上:
def plotHistogram(p, o):
"""
p and o are iterables with the values you want to
plot the histogram of
"""
plt.hist([p, o], color=['g','r'], alpha=0.8, bins=50)
plt.show()