Home > database >  How can I delete a line from a plot by clicking on the legend using matplotlib?
How can I delete a line from a plot by clicking on the legend using matplotlib?

Time:09-01

Here is my code so far:

import pandas as pd

y = {'aa': [12,15,20,15,2,10,6,8], 'bb' : [12,15,20,15,2,5,9,15] , } 
x = [1,2,3,4,5,6,7,8]

graph = pd.DataFrame(y,x)
graph.plot(kind='line' )

my_plot

CodePudding user response:

Are you using Jupyter Notebook or just a py file?

If you're using Jupyter Notebook, you can do something like this, it will set the alpha of the line you click on to 0. This way, if you want, you can set it up to show the line again at some point (where as .remove would completely remove the line from the figure):

%matplotlib notebook # matplotlib magic to make interactive plots work in JNB

# Your 'onpick' event handler, tells the graph what to do when clicking on the legend
def onpick(event):    
    legend_label = event.artist.get_label()
   
    # If the label of the legend matches that of the line, then set the alpha to 0
    for x in range(len(ax.get_lines())):
        if legend_label == ax.get_lines()[x].get_label():
            ax.get_lines()[x].set_alpha(0)
    
import pandas as pd
import matplotlib.pyplot as plt

y = {'aa': [12,15,20,15,2,10,6,8], 'bb' : [12,15,20,15,2,5,9,15] , } 
x = [1,2,3,4,5,6,7,8]
df = pd.DataFrame(y,x)

fig, ax = plt.subplots()
ax.plot(df.aa, label='aa') # line 1
ax.plot(df.bb, label='bb') # line 2

# Set up the picker for the legend elements
for legend in plt.legend().get_lines():
    legend.set_picker(5)

# Activate/connect the graph to the onpick function
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()

If you're working in a py file, use this code instead. The main difference is fig.canvas.draw() being needed to actually update the plot after clicking on it.

def onpick(event):    
    legend_label = event.artist.get_label()
   
    for x in range(len(ax.get_lines())):
        if legend_label == ax.get_lines()[x].get_label():
            ax.get_lines()[x].set_alpha(0)
            fig.canvas.draw()
    
import pandas as pd
import matplotlib.pyplot as plt

y = {'aa': [12,15,20,15,2,10,6,8], 'bb' : [12,15,20,15,2,5,9,15] , } 
x = [1,2,3,4,5,6,7,8]
df = pd.DataFrame(y,x)

fig, ax = plt.subplots()
ax.plot(df.aa, label='aa')
ax.plot(df.bb, label='bb')

for legend in plt.legend().get_lines():
    legend.set_picker(5)
fig.canvas.mpl_connect('pick_event', onpick)
plt.show()

Original Graph: enter image description here

After bb is clicked: enter image description here

After aa is clicked: enter image description here

  • Related