使用Matplotlib绘制多个序列时,使用颜色列表。

4
我想将pandas DataFrame的多列添加到matplotlib轴上,并使用颜色名称列表定义颜色。 当将列表传递给颜色参数时,我会收到一个值错误:无效的RGBA参数。 以下MWE重现了此错误:
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches

df = pd.DataFrame({'0':[0,1,0],'a':[1,2,3],'b':[2,4,6],'c':[5,3,1]})
colors = ['r','g','b']
fig, ax = plt.subplots()
ax.bar(df.index.values,df['0'].values, color = 'y')
ax2 = ax.twinx()
h = ax2.plot(df.index.values, df[['a','b','c']].values, color = colors)
handles = [mpatches.Patch(color='y')]
handles = handles + h
labels = df.columns()
lgd=ax.legend(handles,labels,loc='center left', bbox_to_anchor=(1.1, 0.5), ncol=1, fancybox=True, shadow=True, fontsize=ls)
plt.savefig('test.png', bbox_extra_artists=(lgd,tbx), bbox_inches='tight')
1个回答

6

Matplotlib的plot函数的color参数只接受单个颜色。可选项:

  • An easy option is to use a color cycler instead

    ax2.set_prop_cycle('color',colors )
    h = ax2.plot(df.index.values, df[['a','b','c']].values)
    
  • You could also loop over the lines after plotting,

    h = ax2.plot(df.index.values, df[['a','b','c']].values)
    for line, color in zip(h,colors):
        line.set_color(color)
    
  • Finally consider using the pandas plotting wrapper,

    df[['a','b','c']].plot(ax = ax2, color=colors)
    
所有选项结果都会生成相同的图表。 enter image description here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接