使用从颜色图中获取的颜色绘制直方图

问题描述 投票:0回答:4

我想绘制一个简单的一维直方图,其中条形图应遵循给定颜色图的颜色编码。

这是一个

MWE

import numpy as n
import matplotlib.pyplot as plt

# Random gaussian data.
Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5

# This is the colormap I'd like to use.
cm = plt.cm.get_cmap('RdYlBu_r')

# Plot histogram.
n, bins, patches = plt.hist(data, 25, normed=1, color='green')

plt.show()

输出这个:

enter image description here

我希望各列遵循

green
中定义的颜色图和
cm
的值给出的颜色编码,而不是整个直方图的颜色为
bins
。这意味着根据所选的颜色图RdYlBu_r,接近零的箱(
不是
高度而是位置)应该看起来更蓝,而接近1的箱看起来更红。

由于

plt.histo
不接受
cmap
参数,我不知道如何告诉它使用
cm
中定义的颜色图。

python matplotlib histogram
4个回答
54
投票

hist
命令返回补丁列表,因此您可以迭代它们并设置它们的颜色,如下所示:

import numpy as n
import matplotlib.pyplot as plt

# Random gaussian data.
Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5

# This is the colormap I'd like to use.
cm = plt.cm.get_cmap('RdYlBu_r')

# Plot histogram.
n, bins, patches = plt.hist(data, 25, normed=1, color='green')
bin_centers = 0.5 * (bins[:-1] + bins[1:])

# scale values to interval [0,1]
col = bin_centers - min(bin_centers)
col /= max(col)

for c, p in zip(col, patches):
    plt.setp(p, 'facecolor', cm(c))

plt.show()

要获取颜色,您需要使用 0 到 1 之间的值调用颜色图。结果图:

enter image description here


19
投票

另一种方法是使用

plt.bar
它接受颜色列表。要确定宽度和高度,您可以使用
numpy.histogram
。您可以通过查找 x 值的范围并将其从 0 缩放到 1 来使用颜色图。

import numpy as n
import matplotlib.pyplot as plt

# Random gaussian data.
Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5

# This is the colormap I'd like to use.
cm = plt.cm.get_cmap('RdYlBu_r')

# Get the histogramp
Y,X = n.histogram(data, 25, normed=1)
x_span = X.max()-X.min()
C = [cm(((x-X.min())/x_span)) for x in X]

plt.bar(X[:-1],Y,color=C,width=X[1]-X[0])
plt.show()

enter image description here


17
投票

虽然这不是您所要求的,但如果其他人偶然发现了这一点(就像我一样)寻找通过垃圾箱的高度而不是顺序进行着色的方法,则基于 Bas 的答案的以下代码将起作用:

import numpy as np
import matplotlib.pyplot as plt

Ntotal = 1000
data = 0.05 * np.random.randn(Ntotal) + 0.5
cm = plt.cm.get_cmap('RdYlBu_r')

n, bins, patches = plt.hist(data, 25, normed=1, color='green')
# To normalize your values
col = (n-n.min())/(n.max()-n.min())
for c, p in zip(col, patches):
    plt.setp(p, 'facecolor', cm(c))
plt.show()

enter image description here


2
投票

我喜欢 Bas Swinckels 的答案,但考虑到颜色图 cm 将 0 到 1 之间的值作为参数,更简单的算法如下

import matplotlib.pyplot as plt

Ntotal = 1000
data = 0.05 * n.random.randn(Ntotal) + 0.5

cm = plt.cm.RdBu_r

n, bins, patches = plt.hist(data, 25, normed=1, color='green')
for i, p in enumerate(patches):
    plt.setp(p, 'facecolor', cm(i/25)) # notice the i/25

plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.