1

I would like to limit the size of the legend in MatPlotLib to scale with a figure. After this, I would like to enable scrolling within the legend to see any cut off data. This is regarding two legends, each corresponding to a subplot. A picture is attached to show the exact setup:

image

In this image, you can see that the legends are overlapping each other, as well as being cut off by the bottom of the frame.

Here is the python code used to obtain the figure:

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

fig, axes = plt.subplots(2, figsize=(9,6))

x = [i for i in range(100)]
y_data = []
for i in range(1,15):
    temp = []
    for j in x:
        temp.append(i * j)
    y_data.append(temp)

for line in y_data:
    axes[0].plot(x, line, '.')
    axes[1].plot(x, line, '.')

axes[0].legend(x, bbox_to_anchor=(1.02, 0, 0.07, 1))
axes[1].legend(x, bbox_to_anchor=(1.02, 0, 0.07, 1))

plt.show() 

I would like to modify this code so that the legend is smaller, and so that if there are a great amount of lines in the legend, the data that is not within the confines of the legend can be scrolled to.

I attempted to use the ideas here: Fix size of legend in matplotlib, but it did not seem to scale with two subplots. Setting the height and width in bbox_to_anchor also did not seem to constrain the legend - only move it.

How can I accomplish this?

William Miller
  • 9,839
  • 3
  • 25
  • 46
Nicholas
  • 11
  • 2
  • You will need to read and understand the [event guide](https://matplotlib.org/users/event_handling.html) and you will need to understand what a `clip_path` is and how to use it. That will allow you to get started on this. – ImportanceOfBeingErnest Mar 24 '20 at 20:18
  • An alternative idea is to allow multiple columns in the legends `ax.legend(...., ncol=3)`. Or to use the [mplcursors](https://mplcursors.readthedocs.io/en/stable/) library to show additional information while hovering. Both will be easier to implement, and friendlier to the user. – JohanC Mar 24 '20 at 20:57
  • were you able to figure it out? i have the same problem. My image has 100 classes and there is no way to fit it inside side by side with the plots – Daniel Vilas-Boas Feb 06 '21 at 20:56

0 Answers0