Reputation: 8950
I am creating a stacked plot. I understand, from experimenting myself and from researching online, that adding labels to a stacked plot is messy, but I have managed to pull it off with the code below.
My question is: how do I retrieve the color cycle used to create the stacked plot, so that I can assign the right colours to the legend?
Right now field 1 is blueish, field 2 greenish, but both labels appear in the first colour. I can force specific colours to both the plot and the legends, but I quite like the default colour cycle and would like to keep using it.
df=pd.DataFrame(np.ones((10,2)),columns=['field1','field2'])
fig,ax=plt.subplots()
plt.suptitle('This is a plot of ABCDEF')
ax.stackplot(df.index,df.field1,df.field2]
patch1=matplotlib.patches.Patch(color='red',label= 'field 1')
patch2=matplotlib.patches.Patch(color='blue', label ='field 2')
plt.legend(handles=[patch1,patch2])
The closest to a solution I have found is: Get matplotlib color cycle state but, if I understand correctly, the order of the colours is not preserved. The problem is that
ax._get_lines.color_cycle
returns an iterator, not a list, so I can't easily do something like
colour of patch 1 = ax._get_lines.color_cycle[0]
Thanks!
Upvotes: 1
Views: 973
Reputation: 3972
You can get the colors from the polycollection object made by stackplot:
fields = ax.stackplot(df.index,df.field1,df.field2)
colors = [field.get_facecolor()[0] for field in fields]
patch1=mpl.patches.Patch(color=colors[0],label= 'field 1')
patch2=mpl.patches.Patch(color=colors[1], label ='field 2')
Upvotes: 2