How to pick unique colors of histogram bars in matplotlib?

 ̄綄美尐妖づ 提交于 2019-12-01 02:19:28

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/25396786/how-to-pick-unique-colors-of-histogram-bars-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!