1

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!

Community
  • 1
  • 1
Pythonista anonymous
  • 8,140
  • 20
  • 70
  • 112
  • Any reason you can't make a list, like: `list(ax._get_lines.color_cycle)`, from the iterator? – CT Zhu Aug 03 '15 at 15:07
  • I don't know why, but it doesn't work. I tried to run it, and python seems to get stuck: after more than 1 minute, still nothing. It may have to do with one of the many undocumented or poorly documented features of matplotlib. If anyone has an explanation as to why it doesn't work, I'd be most interested. – Pythonista anonymous Aug 03 '15 at 15:39
  • 1
    PS actually, trying colors= list(ax._get_lines.color_cycle) crashed the whole IDE (Spyder) 3 times and I have no clue why... – Pythonista anonymous Aug 03 '15 at 15:44

1 Answers1

2

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')
Amy Teegarden
  • 3,842
  • 20
  • 23