更改 matplotlib 样式表中的颜色数

change the number of colors in matplotlib stylesheets

我正在使用 matplotlib 绘制几张图表以用于出版物,我需要所有图表都具有相同的样式。有些图表有超过 6 个类别,我注意到,默认情况下,它不会绘制超过 6 种不同的颜色。 7 或更多,我开始有重复的颜色。

例如

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

不包含超过 6 种不同的颜色可能是出于认知原因,但如果我需要,我该怎么做?我尝试了不同的样式表(seaborn、ggplot、classic),但似乎都具有相同的 "limitation".

我需要更改 colormap/stylesheet 吗?理想情况下,我想使用定性颜色图(我正在绘制的类别中没有顺序)并使用预先存在的...我不是很好选择颜色。

谢谢!

默认情况下,matplotlib 将循环使用一系列六种颜色。如果您想更改默认颜色(或颜色数量),您可以使用 cycler 循环显示您想要的颜色而不是默认颜色。

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

更好的方法是在创建 plot 时手动指定绘图颜色,这样您制作的每个绘图都不必使用相同的颜色。

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

或者您可以在创建后更改颜色

h = plt.plot([1,2,3])
h.set_color('r')
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)

这基本上是从Plotting with more colors in matplotlib. check the document of colormap and its example page复制过来的。