简体   繁体   English

如何在matplotlib中选择直方图条的独特颜色?

[英]How to pick unique colors of histogram bars in matplotlib?

I am trying to plot a several histogram on the same plot but I figured out that some colors are assigned to different series, which bother me a little.我试图在同一个图上绘制几个直方图,但我发现有些颜色被分配给不同的系列,这让我有点困扰。 Is there a way of forcing color bars to be unique ?有没有办法强制颜色条是唯一的?

That works for small data set, but when I use a lot of data, I see this problem coming back这适用于小数据集,但是当我使用大量数据时,我发现这个问题又回来了

here is an example, the blue color is assigned twice to two different data samples这是一个例子,蓝色被分配给两个不同的数据样本两次

在此处输入图片说明

All the examples and the solutions to attribute colors to histograms in matplotlib (at least those I found) are suggesting to normalize x axis between 0 and 1 like this example , but this is not what I want to have because it is very important to have the real values in my case.在 matplotlib 中将颜色归因于直方图的所有示例和解决方案(至少是我发现的那些)都建议像这个示例一样将 x 轴标准化为 0 和 1 之间,但这不是我想要的,因为拥有它非常重要在我的情况下的真正价值。

Is there another solution ?还有其他解决方案吗?

Thanks谢谢

EDIT编辑

One solution I came with is to convert a cmap palette to a numpy array and use pyplot hist color by calling this palette我带来的一个解决方案是将 cmap 调色板转换为 numpy 数组,并通过调用此调色板使用 pyplot hist 颜色

N = len(list_of_samples)
sample_colors = cm.get_cmap('RdYlBu', N)
palette = sample_colors(np.arange(N))

But this works only for hist for plot function I got this error message但这仅适用于绘图函数的 hist 我收到此错误消息

ValueError: to_rgba: Invalid rgba arg "[[ 0.64705884  0.          0.14901961  1.        ]
 [ 0.89187675  0.2907563   0.20000001  1.        ]
 [ 0.98711484  0.64593837  0.36358543  1.        ]
 [ 0.99719888  0.91316527  0.61736696  1.        ]
 [ 0.91316529  0.96638656  0.90868344  1.        ]
 [ 0.63977591  0.82633053  0.90028011  1.        ]
 [ 0.34957983  0.55294117  0.75462185  1.        ]
 [ 0.19215687  0.21176471  0.58431375  1.        ]]"
only length-1 arrays can be converted to Python scalars

A solution for histograms is as follows:直方图的解决方案如下:

import pylab as pl

N, bins, patches = pl.hist(pl.rand(1000), 20)

jet = pl.get_cmap('jet', len(patches))

for i in range(len(patches)):
    patches[i].set_facecolor(jet(i))

Result:结果:

在此处输入图片说明

I hope that's what you are looking for.我希望这就是你正在寻找的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM