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

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

1

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

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

但问题是,对于每个间隔,只会出现具有最大值的条,而另一个则隐藏起来。我想知道如何用不同的颜色同时绘制两个柱状图。

这里有一个工作示例:

1

2

3

4

5

6

7

8

9

10

11

12

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

acUlv.png

为了以防万一,在密谋之前设置pyplot.hold(True)不是个好主意吗?

不确定在matplotlib配置参数中是否设置了hold(true),或者pyplot在默认情况下的行为是这样的,但是对于我来说,代码的工作方式是这样的。这段代码是从一个更大的应用程序中提取出来的,目前还没有给出任何问题。不管怎样,在编写代码时我已经问了一个很好的问题

@华金:我怎么能指定x为蓝色,y为红色?

@AMC调用hist时使用相应的颜色关键字

当我复制带有边缘颜色的图条时,默认为None。如果您想要与图中所示相同的设计,您可以在两者中设置edgecolor参数,例如将k参数设置为黑色。图例的过程类似。

@Joaquin有两个不同的轴(一个在左边代表蓝色,一个在右边代表绿色)来更好地看到这两组数据是很有趣的。

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

1

2

3

4

5

6

7

8

9

10

11import 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】:更新后允许绘制不同尺寸的阵列,如@randomatic_o zeitgeist建议的那样。

如何从两个大小不同的数据数组在同一个图上制作柱状图?

我担心,如果没有一些较低级别的Matplotlib修补(即不能直接从具有较高级别功能(如plt.hist)的盒子中执行),目前这是不可能的。一个简单的解决方法是使用@joaquin的答案。另一个(可能更好的)解决方法是用np.nan填充不同大小的数组,这样您就可以使data,但即使Matplotlib失败了。有一个待定的请求,地址是:github.com/matplotlib/matplotlib/pull/7133

我用plt.hist([x, y], color=['g','r'], alpha=0.8, bins=50)解决了它

@古斯塔沃贝泽拉,如何使用plt.hist为每个柱状图生成一个pdf文件?我使用pandas.read_csv加载了我的数据,文件有36列和100行。所以我想要100份PDF文件。

@西格尔,这是相当离题的。请谷歌或问一个新问题。这似乎是相关的:stackoverflow.com/questions/11328958/…

@随机时代精神:你考虑过根据你的评论写一个答案吗?对我来说,这是唯一有用的建议。

@随机时代精神我同意@pasbi。我用了你的评论和熊猫数据框架,因为我需要不同的重量,由于纳米。与x=np.array(df.a)和y=np.array(df.b.dropna())一起,基本上是plt.hist([x, y], weights=[np.ones_like(x)/len(x), np.ones_like(y)/len(y)])。

@Grinsbaccchen-完成,这里

如果您的样本大小大不相同,您可能希望使用双轴绘图,以便更好地比较分布。见下文。

@古斯塔沃贝泽拉有两个不同的轴(一个在左边代表蓝色,一个在右边代表绿色),以便更好地看到这两组数据。

@请参阅安德鲁的回答。

如果您有不同的样本大小,可能很难将分布与单个Y轴进行比较。例如:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15import 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获取柱状图数据,清除轴,然后在两个单独的轴上重新绘制柱状图数据(移动箱边缘,使其不重叠):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

氧化镁

这是一个很好的简短答案,除了您还应该添加如何使每个勾号标签上的条居中之外。

以下是一种简单的方法,当数据大小不同时,将两个柱状图(条形图并排)绘制在同一个图上:

1

2

3

4

5

6

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

作为古斯塔沃·贝泽拉回答的补充:

如果要对每个柱状图进行标准化(MPL<=2.1的normed和MPL<=3.1的density,则不能只使用normed/density=True,需要为每个值设置权重:

1

2

3

4

5

6

7

8

9

10

11

12

13

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

pEXV5.png

作为比较,与默认权重和density=True完全相同的x和y矢量:

gDJsL.png

太棒了-我第一次看到提到的……谢谢!

@欢迎你!

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

1

2

3

4

5

6

7

8import 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)

氧化镁

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

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

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

小精灵

或者,您可以使用子批次。

不同的是,使用hist可以绘制频率图。也许你应该示范一下怎么做。熊猫+条形图的频率=hist()

以防万一你有熊猫(import pandas as pd只)或者可以使用它:

1

2

3

4test = 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()

我相信如果要比较的直方图有不同的样本大小,那么使用熊猫是行不通的。这通常也是使用标准化柱状图的上下文。

此问题之前已得到解答,但希望添加另一个快速/简单的解决方案,以帮助其他访问者解决此问题。

1

2

3import seasborn as sns

sns.kdeplot(mydata1)

sns.kdeplot(mydata2)

这里有一些有用的例子来比较kde和柱状图。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值