tos
tos

Reputation: 996

Matplotlib demo code not working

I am trying to run demo code from Matplotlib: the legend_picking example.

This code is supposed to hide and show plot lines when the legend is clicked.

It seems that event 'pick_event' is not fired when I click on the line on the legend. I have no problem with the simple picking example

"""
# Enable picking on the legend to toggle the legended line on and off
"""
import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 0.2, 0.1)
y1 = 2*np.sin(2*np.pi*t)
y2 = 4*np.sin(2*np.pi*2*t)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('Click on legend line to toggle line on/off')
line1, = ax.plot(t, y1, lw=2, color='red', label='1 HZ')
line2, = ax.plot(t, y2, lw=2, color='blue', label='2 HZ')
leg = ax.legend(loc='upper left', fancybox=True, shadow=True)
leg.get_frame().set_alpha(0.4)


# we will set up a dict mapping legend line to orig line, and enable
# picking on the legend line
lines = [line1, line2]
lined = dict()
for legline, origline in zip(leg.get_lines(), lines):
    legline.set_picker(5)  # 5 pts tolerance
    lined[legline] = origline


def onpick(event):
    # on the pick event, find the orig line corresponding to the
    # legend proxy line, and toggle the visibilit
    legline = event.artist
    origline = lined[legline]
    vis = not origline.get_visible()
    origline.set_visible(vis)
    # Change the alpha on the line in the legend so we can see what lines
    # have been toggled
    if vis:
        legline.set_alpha(1.0)
    else:
        legline.set_alpha(0.2)
    fig.canvas.draw()

fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

Upvotes: 1

Views: 992

Answers (2)

ev-br
ev-br

Reputation: 26040

Which version of matplotlib are you running? Works just fine for me (version 1.1.0). There are multiple examples on the sourceforge site which do not work for versions below 1.0. To find out the version number, use

import matplotlib
print matplotlib.__version__

Upvotes: 1

lbolla
lbolla

Reputation: 5411

It does work. Just click on the lines in the legend.

The script is supposed to toggle transparency of the graphs, by clicking on their lines in the legend.

Upvotes: 0

Related Questions