change the number of colors in matplotlib stylesheets

4k views Asked by At

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!

2

There are 2 answers

1
Dyno Fu On BEST ANSWER
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

colors = plt.cm.jet(np.linspace(0, 1, 10))

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

this is basically copied from Plotting with more colors in matplotlib. check the document of colormap and its example page.

1
Suever On

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')