Skip to content Skip to sidebar Skip to footer

Matplotlib Legend Picking With Pandas Dataframe Doesn't Work

I have the following dataframe: >>> 60.1 65.5 67.3 74.2 88.5 ... A1 0.45 0.12 0.66 0.76 0.22 B4 0.22 0.24 0.12 0.56 0.34 B7 0.12

Solution 1:

Firstly, you need to extract all line2D objects on the figure. You can get them by using ax.get_lines(). Here the example:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
ts = ts.cumsum()
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
df = df.cumsum()
fig, ax = plt.subplots()
df.plot(ax=ax)
lines = ax.get_lines()
leg = ax.legend(fancybox=True, shadow=True)
lined = {}  # Will map legend lines to original lines.
for legline, origline in zip(leg.get_lines(), lines):
    legline.set_picker(True)  # Enable picking on the legend line.
    lined[legline] = origline

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

fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()

Post a Comment for "Matplotlib Legend Picking With Pandas Dataframe Doesn't Work"