Matplotlib 如何给占数据50%的条形图上色?

Matplotlib 如何给占数据50%的条形图上色?,matplotlib,Matplotlib,我正在绘制一些数据点的柱状图,其中条形图高度是该箱子占整个数据的百分比: x = normal(size=1000) hist, bins = np.histogram(x, bins=20) plt.bar(bins[:-1], hist.astype(np.float32) / hist.sum(), width=(bins[1]-bins[0]), alpha=0.6) 结果是: 我希望所有合计为50%数据的条形图采用不同的颜色,例如: (我选择了彩色条,但没有实际检查它们的总和是否

我正在绘制一些数据点的柱状图,其中条形图高度是该箱子占整个数据的百分比:

x = normal(size=1000)
hist, bins = np.histogram(x, bins=20)
plt.bar(bins[:-1], hist.astype(np.float32) / hist.sum(), width=(bins[1]-bins[0]), alpha=0.6)
结果是:

我希望所有合计为50%数据的条形图采用不同的颜色,例如:

(我选择了彩色条,但没有实际检查它们的总和是否增加到50%)


有什么建议吗?

这里是如何用不同的颜色绘制前半个垃圾箱的图,这看起来像你的模拟,但我不确定它是否符合数据的50%(我不清楚你的意思是什么)

输出为:

更新 您要查看的关键方法是
patch.set\u set\u facecolor
。您必须了解,在Axis对象内绘制的几乎所有对象都是面片,因此它具有此方法,下面是另一个示例,我任意选择前3个条以获得另一种颜色,您可以根据您的决定进行选择:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

## the data
N = 5
menMeans = [18, 35, 30, 35, 27]

## necessary variables
ind = np.arange(N)                # the x locations for the groups
width = 0.35                      # the width of the bars

## the bars
rects1 = ax.bar(ind, menMeans, width,
                color='black',
                error_kw=dict(elinewidth=2,ecolor='red'))

for patch in rects1.patches[:3]:
    patch.set_facecolor('red')    

ax.set_xlim(-width,len(ind)+width)
ax.set_ylim(0,45)
ax.set_ylabel('Scores')
xTickMarks = ['Group'+str(i) for i in range(1,6)]
ax.set_xticks(ind)
xtickNames = ax.set_xticklabels(xTickMarks)
plt.setp(xtickNames, rotation=45, fontsize=10)
plt.show() 

请粘贴您已经使用过的代码。第二张图像是一个模型:/I我没有它的代码……这与我正在寻找的非常接近。在我的图表中,每个条代表数据中与该值对应的点的百分比。我想所有的酒吧,总结为50%的数据点是在一个不同的颜色。我试图修改您的代码,但似乎找不到一种方法来规范化条形图以表示数据的百分比(normed=1似乎不这样做),正如我之前所说的,将您编写的代码放在这里,以便能够帮助您。现在,这只是猜测。对不起,我不确定您指的是什么其他代码?我唯一的代码是在问题中提供的…我再次问,50%的数据点是什么意思?如果你有20个点,那么50%是到第10个点,如果你是指累计和,也有一种方法,但你的不那么具体。50%来自数据点,如果柱状图中的第一个条形图表示一个包含4个点的箱子,下一个条形图表示5个点,第三个条形图表示11个点,这三个条形图将被着色,其余的将使用默认颜色。
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

## the data
N = 5
menMeans = [18, 35, 30, 35, 27]

## necessary variables
ind = np.arange(N)                # the x locations for the groups
width = 0.35                      # the width of the bars

## the bars
rects1 = ax.bar(ind, menMeans, width,
                color='black',
                error_kw=dict(elinewidth=2,ecolor='red'))

for patch in rects1.patches[:3]:
    patch.set_facecolor('red')    

ax.set_xlim(-width,len(ind)+width)
ax.set_ylim(0,45)
ax.set_ylabel('Scores')
xTickMarks = ['Group'+str(i) for i in range(1,6)]
ax.set_xticks(ind)
xtickNames = ax.set_xticklabels(xTickMarks)
plt.setp(xtickNames, rotation=45, fontsize=10)
plt.show()