Issue
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 0.47 0.93 0.65 0.21
...
i'm trying to create line plot and to be able to enable/ disable some lines (like to display or hide certain items from the legend). I have found this . here the example is with numpy and not with pandas dataframe. When I try to apply it on my pandas df I manage to create plot but is not interactive:
%matplotlib notebook
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()
test.T.plot()
fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
I get plot but can't click on the legend items and display or hide them.
My end goal: to be able to display or hide lines interactively from legend using the on_pick function from matplotlib.
edit: I understand that I have problem with this part of the documentation:
lines = [line1, line2]
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
as I see that here the lines are taken "one by one" ut in my script I use pandas and T in order to get each line. not sure how to deall with this.
Solution
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()
Answered By - Yudha Styawan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.