Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the number of colors in matplotlib stylesheets

I am plotting several graphs with matplotlib for a publication and I need that all have the same style. Some graphs have more than 6 categories and I have noticed that, by default, it does not plot more than 6 different colours. 7 or more and I start to have repeated colours.

e.g.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
plt.style.use('seaborn-muted')

df2= pd.DataFrame(np.random.rand(10,8))
df2.plot(kind='bar',stacked=True)
plt.legend(fontsize=13,loc=1)
plt.show()

There is probably a cognitive reason not to include more than 6 different colours, but if I need to, How can I do it? I have tried different stylesheets (seaborn, ggplot, classic) and all have seem to have the same "limitation".

Do I need to change the colormap/stylesheet? Ideally, I would like to use a qualitative colormap (there is no order in the categories that I am plotting) and use a pre-existing one... I am not very good choosing colours.

thanks!

like image 971
Nabla Avatar asked Mar 11 '23 05:03

Nabla


1 Answers

By default, matplotlib will cycle through a series of six colors. If you want to change the default colors (or number of colors), you can use cycler to loop through the colors you want instead of the defaults.

from cycler import cycler

% Change the default cycle colors to be red, green, blue, and yellow
plt.rc('axes', prop_cycle=(cycler('color', ['r', 'g', 'b', 'y']))

demo here

A better way is just to manually specify plot colors when you create your plot so that not every plot you make has to use the same colors.

plt.plot([1,2,3], 'r')
plt.plot([4,5,6], 'g')
plt.plot([7,8,9], 'b')
plt.plot([10,11,12], 'y')

Or you can change the color after creation

h = plt.plot([1,2,3])
h.set_color('r')
like image 74
Suever Avatar answered Mar 12 '23 18:03

Suever