0
votes

I'm trying to place a legend in a subfigure but I can't manage to do so. Here is an example of what I'm trying to do:

def test():
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    V = 10
    X = range (V)
    char = 'a'
    leg = []
    legp = []
    for i in range (0,5):
        Y = np.random.randn(V)
        ap = ax1.plot(X,Y)
        legp.append(ap)
        char = chr(ord(char)+1)
        leg.append(char)
    fig.legend(legp,leg)
    fig.show()

This yield with empty legend. I also get a bunch of warning messages:

warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(orig_handle),)) /usr/lib/pymodules/python2.7/matplotlib/legend.py:610: UserWarning: Legend does not support [] Use proxy artist instead.

http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist

warnings.warn("Legend does not support %s\nUse proxy artist instead.\n\nhttp://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist\n" % (str(orig_handle),))

I guess this is something to do with this "proxy artist" but the link it points out to the link where learned this to begin with.

For those wondering, I want to include only part of the drawn plots in the legend.

How can I achieve this then?

Edit:
I'm using python 2.7.3 on Ubuntu 12.10 with gnome.

1
Can you print (debug) legp and leg before calling legend()? Your warning tells you that one of these is an empty list (perhaps both), meaning that either your loop isn't properly run, or they append statements don't work as expected. (Also, double check that the code here is exactly the same as the code you.) - user707650
@Evert. I replaced ax1.plot(X,Y) with ax1.plot(X,Y)[0] and this work now. You can read gerogesl's and mine comment thread. Thank you. - Yotam

1 Answers

2
votes

Weird... It seems to work fine with me.

EDIT : The issue came from unpacking the plot return object : ap, = ax1.plot(X,Y)

For more info on the use of the comma :

Matplotlib Legends not working

line, = plot(x,sin(x)) what does comma stand for?

Controling line properties

END OF EDIT

See :

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
V = 10
X = range (V)
char = 'a'
leg = []
legp = []
for i in range (0,5):
    Y = np.random.randn(V)
    ap = ax1.plot(X,Y)
    legp.append(ap)
    char = chr(ord(char)+1)
    leg.append(char)
fig.legend(legp,leg)
plt.show()

And the result : enter image description here