使用从颜色图获取的颜色绘制直方图
我想绘制一个简单的一维直方图,其中条形图应遵循给定颜色图的颜色编码.
I want to plot a simple 1D histogram where the bars should follow the color-coding of a given colormap.
这是一个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()
输出以下内容:
我希望这些列遵循由cm
中定义的色图和bins
的值给出的颜色编码,而不是整个直方图的颜色为green
.这意味着根据选择的颜色图RdYlBu_r
,接近零的垃圾箱(高度不是位置,而是位置)应该看起来更蓝,而更接近红色的垃圾箱应该看起来更蓝.
Instead of the color being green
for the entire histogram, I'd like the columns to follow a color-coding given by the colormap defined in cm
and the values of the bins
. This would mean that bins closer to zero (not in height but in position) should look bluer and those closer to one redder, according to the chosen colormap RdYlBu_r
.
由于plt.histo
不使用cmap
自变量,所以我不知道如何告诉它使用cm
中定义的色图.
Since plt.histo
doesn't take a cmap
argument I don't know how to tell it to use the colormap defined in cm
.
hist
命令返回补丁列表,因此您可以对其进行迭代并设置其颜色,如下所示:
The hist
command returns a list of patches, so you can iterate over them and set their color like so:
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之间的值调用颜色图.结果图:
To get the colors, you need to call the colormap with a value between 0 and 1. Resulting figure: