Sri
Sri

Reputation: 711

How to update the legend from matplotlib toolbar

I am defining a matplotlib plot for a given data. once the plot is displayed, I am trying to change some line property using navigation tool bar edit option.

When I make change say example solid line to dashdotted, the update get reflected on the lines, but the legends are not updated.

How can I capture this event when the apply button is clicked, so i can use this to refresh the legend. At the moment I am capturing a pick_event as a signal to refresh the legends.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('Qt4Agg')


x=np.linspace(0,100,100)
y=np.linspace(100,200,100)
plt.plot(x,y,label='test')
plt.legend()
ax.legend()
plt.show()
#optional code
def on_press(event):
    lines, labels = ax.get_legend_handles_labels()
    ax.legend(lines, labels, loc=0)
    fig.canvas.draw()

cid = fig.canvas.mpl_connect('pick_event', on_press)

Plot image from the above code Plot Image showing modifying line type Plot Image showing the legend is not modified

Upvotes: 4

Views: 8534

Answers (1)

Sri
Sri

Reputation: 711

After a bit of struggle the only easy way to resolve this solution is to add legend refresh as part of the navigation tool bar call back function

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

def home_callback():
    print "home called"
    ax.legend()

x=np.linspace(0,100,100)
y=np.linspace(100,200,100)
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x,y,label='test')
ax.legend()
plt.show()

fm = plt.get_current_fig_manager()

fm.toolbar.actions()[0].triggered.connect(home_callback)

Upvotes: 4

Related Questions