首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用matplotlib在单个图表上绘制两个直方图

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

Stack Overflow用户
提问于 2011-07-29 17:37:09
回答 11查看 473.5K关注 0票数 301

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

代码语言:javascript
复制
n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)

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

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2011-07-29 21:33:45

下面是一个可用的示例:

代码语言:javascript
复制
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()

票数 514
EN

Stack Overflow用户

发布于 2016-09-14 10:41:05

公认的答案给出了带有重叠条的直方图的代码,但如果您希望每个条并排(就像我做的那样),请尝试下面的变体:

代码语言:javascript
复制
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

编辑2018/03/16:根据@stochastic_zeitgeist的建议,更新以允许绘制不同大小的数组

票数 247
EN

Stack Overflow用户

发布于 2017-12-11 18:06:00

在具有不同样本大小的情况下,可能很难将分布与单个y轴进行比较。例如:

代码语言:javascript
复制
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()

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

代码语言:javascript
复制
#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()

票数 35
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6871201

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档