使用 matplotlib 绘制多个系列时使用颜色列表

Nic*_*coH 4 python colors matplotlib pandas

我想将 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')
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 6

matplotlibplotcolor参数仅接受单一颜色。选项:

所有选项都会产生相同的图。

在此输入图像描述