Python matplotlib legend and title are being cliped
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

The legend in in the plot below goes off the chart, l need better control of the plot, legend and title spacing to show all the chart elements. The legend needs to show beside the right hand side of the plot.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

ax.scatter( [50, 50],[10,40], c='blue', s=200, label="#1 cats and dogs")
ax.scatter([100,100], [30,60], c='green', s=200, label="#2 pigs in mud" )
ax.scatter([30,30], [30,60], c='yellow', s=200, label="#3 nothing good")
ax.legend(bbox_to_anchor=(1.01,1), borderaxespad = 0,fontsize=8 )
fig.tight_layout()
plt.title('Scatter')
plt.xlabel('categories')
plt.ylabel('values')
plt.show() 
awarded to dekkard
Tags
python3

Crowdsource coding tasks.

2 Solutions


Hello broadreach,

Instead of using tight layout, you can scale the figure to accommodate other elements.
The new script can be found here.

Let me know if you need anything more.

Thanks,
Vladimir

Thanks, nice and simple. The legend is quite long, can the size of the plot area be controlled so that its size is relative to the length of the legend. In my plot, the legend is clipped on the bottom.
broadreach 22 days ago
Hello broadreach. If we were to resize plot area to the size of the legend, it would be hard to read. I've reduced the size of the legend. Here is the updated code and here is how it looks like. If it looks different on your device, feel free to post the screenshot and device info so I can further look into it. Thanks.
VladimirMikulic 22 days ago
The updated code looks the same as the first. Thanks!
broadreach 22 days ago
Hi, broadreach. If it looks the same that's great. Then, is this the look that you are looking for? Thanks!
VladimirMikulic 22 days ago
All good, thanks!
broadreach 22 days ago
Winning solution

You have to put fig.tight_layout() after all changes to the plot, just before show(), like so:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.scatter( [50, 50],[10,40], c='blue', s=200, label="#1 cats and dogs")
ax.scatter([100,100], [30,60], c='green', s=200, label="#2 pigs in mud" )
ax.scatter([30,30], [30,60], c='yellow', s=200, label="#3 nothing good")
ax.legend(bbox_to_anchor=(1.01,1), borderaxespad = 0,fontsize=8 )

plt.title('Scatter')
plt.xlabel('categories')
plt.ylabel('values')

fig.tight_layout() # <<<

plt.show()

Also, as documented in the Tight Layout Guide:

Note that matplotlib.pyplot.tight_layout() will only adjust the subplot params when it is called. In order to perform this adjustment each time the figure is redrawn, you can call fig.set_tight_layout(True), or, equivalently, set rcParams["figure.autolayout"] (default: False) to True.
View Timeline