Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend not showing up in Matplotlib stacked area plot

I am creating a stacked line/area plot using plt.fill_between() method of the pyplot, and after trying so many things I am still not able to figure why it is not displaying any legend or labels (even when I provide them in the code). Here is the code:

import matplotlib.pyplot as plt import numpy  a1_label = 'record a1' a2_label = 'record a2'  a1 = numpy.linspace(0,100,40) a2 = numpy.linspace(30,100,40)  x = numpy.arange(0, len(a1), 1)  plt.fill_between(x, 0, a1, facecolor='green') plt.fill_between(x, a1, a2, facecolor='red') plt.title('some title') plt.grid('on') plt.legend([a1_label, a2_label]) plt.show() 

Here is the image generated (note that the legend shows empty box instead of labels): empty legend box at the top

Help!

like image 361
khan Avatar asked Jan 26 '13 05:01

khan


People also ask

How do you display the legend outside the plot?

In Matplotlib, to set a legend outside of a plot you have to use the legend() method and pass the bbox_to_anchor attribute to it. We use the bbox_to_anchor=(x,y) attribute. Here x and y specify the coordinates of the legend.

How do I fix the legend position in Matplotlib?

To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.

How do you plot a stacked area in Python?

A basic stacked area chart can be plotted by the stackplot() function of matplotlib. The parameters passed to the function are: x : x axis positions. y : y axis positions.


2 Answers

The fill_between() command creates a PolyCollection that is not supported by the legend() command.

Therefore you will have to use another matplotlib artist (compatible with legend()) as a proxy, without adding it to the axes (so the proxy artist will not be drawn in the main axes) and feed it to the legend function. (see the matplotlib legend guide for more details)

In your case, the code below should fix your problem:

from matplotlib.patches import Rectangle  p1 = Rectangle((0, 0), 1, 1, fc="green") p2 = Rectangle((0, 0), 1, 1, fc="red") legend([p1, p2], [a1_label, a2_label]) 

image

like image 163
gcalmettes Avatar answered Sep 20 '22 03:09

gcalmettes


gcalmettes's answer was a helpful start, but I wanted my legend to pick up the colors that the stackplot had automatically assigned. Here's how I did it:

polys = pyplot.stackplot(x, y) legendProxies = [] for poly in polys:     legendProxies.append(pyplot.Rectangle((0, 0), 1, 1, fc=poly.get_facecolor()[0])) 
like image 31
Andrew M. Greene Avatar answered Sep 21 '22 03:09

Andrew M. Greene