Hadarsi320
Hadarsi320

Reputation: 393

Is there a way to make the legend in matplotlib fit better within the plot?

I need to plot a line plot with multiple lines.

Due to a large number of lines, the legend gets so large that it hides some of the lines, is there a way to automatically set the y ticks so that there will be enough room in the plot for the legend to fit properly?

Example plot:

Example plot

Thank you.

Upvotes: 1

Views: 1348

Answers (1)

meTchaikovsky
meTchaikovsky

Reputation: 7666

You can adjust the xlim and the dict prop, for example

x = np.linspace(1,10,10)
y = x + np.random.rand(10,10)
labels = list('abcdefghij')

fig,ax = plt.subplots(figsize=(12,6))
ax.plot(x,y,'-o')

ax.set_xlim(1,11)
ax.legend(labels,loc='upper right', prop={'size': 10})

plot

Tuning ax.set_xlim to leave enough space for the legend, and the size of the legend is controlled by prop={'size':10}

Upvotes: 1

Related Questions