如何为占数据 50% 的条形着色? [英] How to color bars who make up 50% of the data?

查看:38
本文介绍了如何为占数据 50% 的条形着色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在绘制一些数据点的直方图,其中条形高度是整个数据中该bin的百分比:

I am plotting a histogram for some data points with bar heights being the percentage of that bin from the whole data:

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% 数据的所有条形都采用不同的颜色,例如:

I would like all bars that sum up to be 50% of the data to be in a different color, for example:

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

(I selected the colored bars without actually checking whether their sum adds to 50%)

任何建议如何做到这一点?

Any suggestions how to accomplish this?

推荐答案

在这里,您可以用不同的颜色绘制垃圾箱的前半部分,这看起来像您的模型,但是我不确定它是否符合%50数据(我不清楚您的意思是什么).

Here is how you can plot the first half of the bins with a different color, this looks like your mock, but I am not sure it complies to %50 of the data (it is not clear to me what do you mean by that).

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

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

# the histogram of the data
n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)


# now that we found the index we color all the beans smaller than middle index
for p in patches[:len(bins)/2]:
    p.set_facecolor('red')

# hist uses np.histogram under the hood to create 'n' and 'bins'.
# np.histogram returns the bin edges, so there will be 50 probability
# density values in n, 51 bin edges in bins and 50 patches.  To get
# everything lined up, we'll compute the bin centers
bincenters = 0.5*(bins[1:]+bins[:-1])
# add a 'best fit' line for the normal PDF
y = mlab.normpdf( bincenters, mu, sigma)
l = ax.plot(bincenters, y, 'r--', linewidth=1)

ax.set_xlabel('Smarts')
ax.set_ylabel('Probability')
ax.set_xlim(40, 160)
ax.set_ylim(0, 0.03)
ax.grid(True)

plt.show()

输出为:

您要查看的关键方法是 patch.set_set_facecolor .您必须了解,您在axis对象中绘制的几乎所有内容都是Patch,因此它具有此方法,这是另一个示例,我任意选择前3个小节以使用另一种颜色,您可以根据自己的选择进行选择决定:

The key method you want to look at is patch.set_set_facecolor. You have to understand that almost everything you plot inside the axes object is a Patch, and as such it has this method, here is another example, I arbitrary choose the first 3 bars to have another color, you can choose based on what ever you decide:

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

这篇关于如何为占数据 50% 的条形着色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆