我用一个文件中的数据创建了一个直方图,没有问题。现在我想在同一直方图中叠加来自另一个文件的数据,所以我这样做

n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)

但问题是,对于每个区间,只有最高值的条出现,而另一个条被隐藏。我想知道如何用不同的颜色同时绘制两个直方图。


当前回答

听起来你可能只需要一个柱状图:

http://matplotlib.sourceforge.net/examples/pylab_examples/bar_stacked.html http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html

或者,您可以使用子情节。

其他回答

听起来你可能只需要一个柱状图:

http://matplotlib.sourceforge.net/examples/pylab_examples/bar_stacked.html http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html

或者,您可以使用子情节。

以防你有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()

你应该使用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)

绘制两个重叠的直方图(或更多)会导致一个相当混乱的图。我发现使用阶梯直方图(又名空心直方图)可以大大提高可读性。唯一的缺点是在matplotlib中,步骤直方图的默认图例没有正确格式化,所以可以像下面的例子那样编辑它:

import numpy as np                   # v 1.19.2
import matplotlib.pyplot as plt      # v 3.3.2
from matplotlib.lines import Line2D

rng = np.random.default_rng(seed=123)

# Create two normally distributed random variables of different sizes
# and with different shapes
data1 = rng.normal(loc=30, scale=10, size=500)
data2 = rng.normal(loc=50, scale=10, size=1000)

# Create figure with 'step' type of histogram to improve plot readability
fig, ax = plt.subplots(figsize=(9,5))
ax.hist([data1, data2], bins=15, histtype='step', linewidth=2,
        alpha=0.7, label=['data1','data2'])

# Edit legend to get lines as legend keys instead of the default polygons
# and sort the legend entries in alphanumeric order
handles, labels = ax.get_legend_handles_labels()
leg_entries = {}
for h, label in zip(handles, labels):
    leg_entries[label] = Line2D([0], [0], color=h.get_facecolor()[:-1],
                                alpha=h.get_alpha(), lw=h.get_linewidth())
labels_sorted, lines = zip(*sorted(leg_entries.items()))
ax.legend(lines, labels_sorted, frameon=False)

# Remove spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# Add annotations
plt.ylabel('Frequency', labelpad=15)
plt.title('Matplotlib step histogram', fontsize=14, pad=20)
plt.show()

如您所见,结果看起来非常干净。这在重叠两个以上的直方图时尤其有用。根据变量的分布方式,这最多可以适用于5个重叠的分布。除此之外,还需要使用另一种类型的情节,比如这里介绍的其中一种。

下面是一个简单的方法来绘制两个直方图,当数据大小不同时,它们的柱状图并排在同一个图上:

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()