Reputation: 1415
I would like to add multiple columns of a pandas DataFrame to a matplotlib axis and define the colors using a list of color names. When passing a list to the color argument I get a value error: Invalid RGBA argument. The following MWE reproduces this error:
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')
Upvotes: 4
Views: 3368
Reputation: 339250
The matplotlib plot
's color
argument only accepts a single color. Options:
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)
All options result in the same plot.
Upvotes: 6