如何为构成50%数据的彩条?

时间:2014-01-20 06:55:04

标签: 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)

结果是:

enter image description here

我希望所有数据总和为50%的数据采用不同的颜色,例如:

enter image description here

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

有任何建议如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

以下是如何使用不同的颜色绘制前半部分的箱子,这看起来像你的模拟,但我不确定它是否符合%50的数据(我不清楚你是什么意思那个)。

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

输出是:

enter image description here

更新

您要查看的关键方法是patch.set_set_facecolor。你必须要明白,你在轴对象内绘制的几乎所有东西都是一个补丁,因此它有这个方法,这是另一个例子,我任意选择前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() 

barplot