使用matplotlib在单个图表上绘制两个直方图

2024-10-03 21:27:58 发布

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

我用一个文件中的数据创建了一个直方图,没有问题。现在我想把另一个文件中的数据叠加到同一个柱状图中,所以我做了类似的事情

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

但问题是,对于每个间隔,只有具有最高值的条显示,而另一条隐藏。我想知道我怎么能用不同的颜色同时绘制两个直方图


Tags: 文件数据间隔颜色绘制ax直方图事情
3条回答

接受的答案给出了带有重叠条的直方图代码,但如果您希望每个条并排(如我所做的),请尝试以下变化:

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

enter image description here

参考:http://matplotlib.org/examples/statistics/histogram_demo_multihist.html

编辑[2018/03/16]:根据@Randomic_zeitgeist的建议,更新以允许绘制不同尺寸的阵列

如果样本大小不同,可能很难用单个y轴比较分布。例如:

import numpy as np
import matplotlib.pyplot as plt

#makes the data
y1 = np.random.normal(-2, 2, 1000)
y2 = np.random.normal(2, 2, 5000)
colors = ['b','g']

#plots the histogram
fig, ax1 = plt.subplots()
ax1.hist([y1,y2],color=colors)
ax1.set_xlim(-10,10)
ax1.set_ylabel("Count")
plt.tight_layout()
plt.show()

hist_single_ax

在这种情况下,可以在不同的轴上绘制两个数据集。为此,可以使用matplotlib获取直方图数据,清除轴,然后在两个单独的轴上重新绘制(移动箱子边缘,使其不重叠):

#sets up the axis and gets histogram data
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.hist([y1, y2], color=colors)
n, bins, patches = ax1.hist([y1,y2])
ax1.cla() #clear the axis

#plots the histogram data
width = (bins[1] - bins[0]) * 0.4
bins_shifted = bins + width
ax1.bar(bins[:-1], n[0], width, align='edge', color=colors[0])
ax2.bar(bins_shifted[:-1], n[1], width, align='edge', color=colors[1])

#finishes the plot
ax1.set_ylabel("Count", color=colors[0])
ax2.set_ylabel("Count", color=colors[1])
ax1.tick_params('y', colors=colors[0])
ax2.tick_params('y', colors=colors[1])
plt.tight_layout()
plt.show()

hist_twin_ax

这里有一个工作示例:

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

enter image description here

相关问题 更多 >