Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Scroll button to matlibplot axes legend

I am working on a Tkinter and matplotlib integrated GUI, I am plotting 128 lines on same matplotlib graph. In order to distinguish these lines, I am adding data legend using the following line.

matplotlib.axis.legend(handle, self.data.label, loc='center left', bbox_to_anchor=(1, 0.5), title='Data series', prop={'size': 10}, fancybox=True ) 

The legend works perfectly fine but when I try to add more than 15 elements to it, its length keeps on increasing and the labels added above and below of the visible 15 are not viable.

I checked the scroll option from the matplotlib.axes.Axes.legend documentation was unable to find any such option. Is it possible to add a scroll option to this legend.?

like image 965
kgangadhar Avatar asked Jun 16 '26 06:06

kgangadhar


1 Answers

If you have a mousewheel you can use a scroll_event to scroll the legend up and down.

import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
import numpy as np

n = 50
t = np.linspace(0,20,51)
data = np.cumsum(np.random.randn(51,n), axis=0)

fig, ax = plt.subplots()
fig.subplots_adjust(right=0.78)
ax.set_prop_cycle(color=plt.cm.gist_rainbow(np.linspace(0,1,data.shape[1])))

for i in range(data.shape[1]):
    ax.plot(t, data[:,i], label=f"Label {i}")


legend = ax.legend(loc="upper left", bbox_to_anchor=(1.02, 0, 0.07, 1))

# pixels to scroll per mousewheel event
d = {"down" : 30, "up" : -30}

def func(evt):
    if legend.contains(evt):
        bbox = legend.get_bbox_to_anchor()
        bbox = Bbox.from_bounds(bbox.x0, bbox.y0+d[evt.button], bbox.width, bbox.height)
        tr = legend.axes.transAxes.inverted()
        legend.set_bbox_to_anchor(bbox.transformed(tr))
        fig.canvas.draw_idle()

fig.canvas.mpl_connect("scroll_event", func)

plt.show()

enter image description here

like image 138
ImportanceOfBeingErnest Avatar answered Jun 17 '26 20:06

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!