简体   繁体   中英

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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