我用一个文件中的数据创建了一个直方图,没有问题。现在我想在同一直方图中叠加来自另一个文件的数据,所以我这样做
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)
但问题是,对于每个区间,只有最高值的条出现,而另一个条被隐藏。我想知道如何用不同的颜色同时绘制两个直方图。
当前回答
以防你有pandas (import pandas as pd)或者可以使用它:
test = pd.DataFrame([[random.gauss(3,1) for _ in range(400)],
[random.gauss(4,2) for _ in range(400)]])
plt.hist(test.values.T)
plt.show()
其他回答
以防你有pandas (import pandas as pd)或者可以使用它:
test = pd.DataFrame([[random.gauss(3,1) for _ in range(400)],
[random.gauss(4,2) for _ in range(400)]])
plt.hist(test.values.T)
plt.show()
接受的答案给出了带有重叠条的直方图的代码,但如果你想要每个条并排(就像我做的那样),请尝试下面的变化:
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-deep')
x = np.random.normal(1, 2, 5000)
y = np.random.normal(-1, 3, 2000)
bins = np.linspace(-10, 10, 30)
plt.hist([x, y], bins, label=['x', 'y'])
plt.legend(loc='upper right')
plt.show()
参考:http://matplotlib.org/examples/statistics/histogram_demo_multihist.html
EDIT[2018/03/16]:更新到允许绘制不同大小的数组,正如@stochastic_zeitgeist所建议的那样
下面是一个简单的方法来绘制两个直方图,当数据大小不同时,它们的柱状图并排在同一个图上:
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()
这里有一个工作示例:
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()
受到Solomon的答案的启发,但要坚持这个与直方图有关的问题,一个干净的解决方案是:
sns.distplot(bar)
sns.distplot(foo)
plt.show()
确保先绘制较高的直方图,否则需要设置plot .ylim(0,0.45),这样较高的直方图就不会被切掉。