使用从颜色图获取的颜色绘制直方图 [英] Plot histogram with colors taken from colormap

查看:61
本文介绍了使用从颜色图获取的颜色绘制直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

这篇关于使用从颜色图获取的颜色绘制直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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