python - 使用matplotlib同时绘制两个直方图

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

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

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

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

8个解决方案

302 votes

这里有一个有效的例子:

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

joaquin answered 2019-04-28T10:32:21Z

97 votes

接受的答案给出了具有重叠条形的直方图的代码,但是如果您希望每个条形并排(就像我一样),请尝试以下变体:

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所示

Gustavo Bezerra answered 2019-04-28T10:33:03Z

15 votes

如果您的样本量不同,则可能难以将分布与单个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()

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

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

Andrew answered 2019-04-28T10:33:36Z

7 votes

下面是一个简单的方法,当数据具有不同的大小时,在同一个图上绘制两个直方图并排其条形图:

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

stochastic_zeitgeist answered 2019-04-28T10:34:02Z

3 votes

听起来你可能只想要一个条形图:

[http://matplotlib.sourceforge.net/examples/pylab_examples/bar_stacked.html]

[http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html]

或者,您可以使用子图。

carl answered 2019-04-28T10:34:48Z

3 votes

万一你有熊猫(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()

serv-inc answered 2019-04-28T10:35:13Z

2 votes

您应该从hist返回的值中使用bins:

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)

Adrien Renaud answered 2019-04-28T10:35:39Z

0 votes

作为Gustavo Bezerra答案的完成:

如果你想要对每个直方图进行标准化(normed为mpl< = 2.1而x为mpl> = 3.1)你不能只使用x,你需要为每个值设置权重:

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向量具有默认权重和density=True:

jojo answered 2019-04-28T10:36:19Z

python画不同颜色的直方图_python - 使用matplotlib同时绘制两个直方图相关推荐

  1. python绘制多个条形图_python – 在Matplotlib中绘制多个直方图 – 颜色或并排条形图...

    问题:在Matplotlib中绘制多个直方图时,我无法区分绘图与另一个绘图 图像问题:** **次要问题:部分左侧标签"计数"不在图像范围内.为什么? 描述 我想绘制3个不同组的直 ...

  2. python画不同颜色的直方图_关于python:使用matplotlib同时绘制两个直方图

    我用文件中的数据创建了一个柱状图,没问题.现在我想把在同一个柱状图中的另一个文件,所以我做了类似 1 2n,bins,patchs = ax.hist(mydata1,100) n,bins,patc ...

  3. python画k线图_Python使用matplotlib绘制k线图(去掉空白日期)

    原标题:Python使用matplotlib绘制k线图(去掉空白日期) 之前研究过使用 matplotlib.finance 中的 candlestick_ohlc() 方法绘制k线图,但是有个很无语 ...

  4. python画两条曲线_python – 在Matplotlib中绘制两个图之间的线

    在许多情况下,来自其他答案的解决方案是次优的(因为只有在计算点之后没有对图进行任何更改时它们才有效). 更好的解决方案是使用专门设计的ConnectionPatch: import matplotli ...

  5. python画有权重网络图_Python可视化之NetworkX绘制网络图\节点关系

    除了Gephi,python的NetworkX也是绘制网络图的利器,后者功能更强大,能兼容Gephi的一些绘制结果,但相应学习成本也更高点.另外似乎还有一个igraph-python库,后期可以学习一 ...

  6. python画k线图_使用Matplotlib轻松绘制股票K线图

    K线图是看懂股票走势的最基本知识,K线分为阴线和阳线,阴线和阳线都包含了最低价.开盘价.最高价和收盘价,一般的K线如下图所示: 度娘说:K线图源于日本德川幕府时代(1603-1867年),被当时日本米 ...

  7. python动态横道图_python的matplotlib.pyplot绘制甘特图

    博主本来就想简单地找一下代码,画一幅甘特图,结果百度之后发现甘特图的代码基本都不是用matplotlib库,但是像柱状图等统计图通常都是用这个库进行绘制的,所以博主就花了一些时间,自己敲了一份代码,简 ...

  8. python画奥运五环小结_python使用turtle库绘制奥运五环

    Turtle库是Python语言中一个很流行的绘制图像的函数库,想象一个小乌龟,在一个横轴为x.纵轴为y的坐标系原点,(0,0)位置开始,它根据一组函数指令的控制,在这个平面坐标系中移动,从而在它爬行 ...

  9. python怎么画条形图-用Matplotlib如何绘制条形图、直方图和散点图

    Matplotlib是一个Python 2D绘图库,它可以在各种平台上以各种硬拷贝格式和交互式环境生成出具有出版品质的图形. 上一篇我们讲解到Matplotlib 中的图例,标题和标签介绍,今天我们开 ...

最新文章

  1. scratch小游戏脚本大全_酷酷带你一起做小游戏--跳一跳
  2. Mybatis 强大的结果映射器ResultMap
  3. D455 如何同时传输视频深度流和惯性单元IMU流?(双管道方法与调用回调方法)
  4. 我做 Fiori 开发经常使用的几个系统,不同的 SAP UI5 版本
  5. Windows驱动开发VXD/WDM/WDF/DDK/WDK的联系和区别
  6. 设计模式之——观察者模式
  7. RDP报表快速打造数据大屏可视化展示系统
  8. 问题 N: [入门OJ]车辆统计(NHOI2011XX1)
  9. python抓取图片数字_从opencv python图像中提取数字
  10. 安卓电子书格式_进阶能力 | 了解常见的电子书格式
  11. wp8.1 java_WP8.1系统升级到Win10 Mobile正式版的方法
  12. 广告系统,业务与架构细节
  13. finclip小程序运行机制与微信小程序运行机制
  14. video标签设计vue视频播放器组件
  15. 程序界的高手传奇(转)
  16. 体系结构 | 五段流水线 | 流水线技术
  17. http请求报错:80 failed to respond
  18. 关于linux系统密码策略的设置
  19. java home not set_hadoop安装及出现JAVA HOME is not set和No such file or directo
  20. 超火爆思维导图工具TheBrain 11到底有哪些值得关注的功能?

热门文章

  1. 决斗场 - 实验吧 隐写术 男神一般都很低调很低调的!!
  2. js 判断给的日期是否为工作日
  3. 高职计算机网络技术课设,计算机专业毕业论文:高职计算机网络技术课堂教学改革研究...
  4. 电脑病毒猛于虎,但这些坏习惯猛于病毒
  5. 《蚂蚁金服11.11:支付宝和蚂蚁花呗的技术架构及实践》阅读心得
  6. 概率质量函数 Vs. 概率密度函数
  7. 在vue中element ui 结合frappe-gantt实现一个简单的甘特图功能
  8. 解决 SVN提交代码中太多其他无关文件的问题
  9. 使用Eclipse集成javap查看类的字节码
  10. 2021,一个应届生的年度总结(附校招面试准备路线)