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)
matplotlibplot的color参数仅接受单一颜色。选项:
一个简单的选择是使用颜色循环仪
ax2.set_prop_cycle('color',colors )
h = ax2.plot(df.index.values, df[['a','b','c']].values)
Run Code Online (Sandbox Code Playgroud)您也可以在绘图后循环遍历线条,
h = ax2.plot(df.index.values, df[['a','b','c']].values)
for line, color in zip(h,colors):
line.set_color(color)
Run Code Online (Sandbox Code Playgroud)最后考虑使用 pandas 绘图包装器,
df[['a','b','c']].plot(ax = ax2, color=colors)
Run Code Online (Sandbox Code Playgroud)所有选项都会产生相同的图。