简体   繁体   中英

Color bars by sample matplotlib

I am trying to color code a bar plot I have by values in a list. I am plotting something like this but I can't figure out how to color it:

x=[1,2,3]
y=[1,2,3]
type=[big,small,big]

p1=plt.bar(x,y)
plt.colorbar(type)

So what I ended up doing was creating a dictionary with defined colors for each of my parameters and then just converted this when plotting like so:

colors = {'C':'b', 'T':'r', 'G':'g', 'A':'y'}
wts.append(colors[x[3]])
p1 = plt.bar(loci, vafs, color=wts)

You may create a dictionary mapping values from the typ list to colors. Then using this dictionary you can create a list of colors to supply to the bar 's color argument.

In order to create a legend, the same dictionary can be used to set the color of legend handles.

import matplotlib.pyplot as plt

x=[1,2,3]
y=[1,2,3]
typ=["big","small","big"]
color = {"big" : "indigo", "small" : "mediumvioletred"}
p1 = plt.bar(x,y, color=[color[t] for t in typ])

handles = [plt.Rectangle((0,0),1,1, color=color[c]) for c in set(typ)]
plt.legend(handles=handles, labels=set(typ))

plt.show()

在此处输入图片说明

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