Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stop Matplotlib from repeating colors? [duplicate]

I have this code:

plist = ['p5', 'p14', 'p23', 'p32', 'p41', 'p50', 'p59', 'p68', 'p77', 'p85', 'p95']


for pltcount in range(len(plist)):
    plt.plot(data1[pltcount], np.exp(data2)[pltcount], marker='o', label=str(plist[pltcount]))
plt.legend()
plt.show()

This is using the plt.style.use('fivethirtyeight') to make the plots nicer. I have found examples where I manually assign the colors. What if I want it to be automatic and from some well-known palettes?

enter image description here

like image 286
maximusdooku Avatar asked Nov 08 '18 00:11

maximusdooku


People also ask

What is the default color cycle Matplotlib?

The default interactive figure background color has changed from grey to white, which matches the default background color used when saving. in your matplotlibrc file.

How do you remove duplicates in Python legend?

You can remove duplicate labels by putting them in a dictionary before calling legend . This is because dicts can't have duplicate keys.

What is Bbox_to_anchor?

bbox_to_anchor=[x0, y0] will create a bounding box with lower left corner at position [x0, y0] . The extend of the bounding box is zero - being equivalent to bbox_to_anchor=[x0, y0, 0, 0] . The legend will then be placed 'inside' this box and overlapp it according to the specified loc parameter.


1 Answers

How about the colors of the rainbow? The key here is to use ax.set_prop_cycle to assign colors to each line.

NUM_COLORS = len(plist)

cm = plt.get_cmap('gist_rainbow')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle('color', [cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)])
# Or,
# ax.set_prop_cycle(color=[cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)])
for i, p in enumerate(plist):
    ax.plot(data1[i], np.exp(data2)[i], marker='o', label=str(p))

plt.legend()
plt.show()

Borrowed from here. Other options possible.

like image 183
cs95 Avatar answered Nov 10 '22 08:11

cs95