The Python Oracle

How to adjust padding with cutoff or overlapping labels

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Horror Game Menu Looping

--

Chapters
00:00 Question
01:56 Accepted answer (Score 659)
02:56 Answer 2 (Score 296)
03:15 Answer 3 (Score 199)
04:05 Answer 4 (Score 10)
04:18 Thank you

--

Full question
https://stackoverflow.com/questions/6774...

Question links:
[image]: https://i.stack.imgur.com/RZ0QA.png
[image]: https://i.stack.imgur.com/pJ9qx.png

Accepted answer links:
[plt.gcf()]: https://matplotlib.org/stable/api/_as_ge...
[plt.gca()]: https://matplotlib.org/stable/api/_as_ge...
[plt.tight_layout()]: https://matplotlib.org/stable/api/_as_ge...
[See matplotlib Tutorials: Tight Layout Guide]: https://matplotlib.org/stable/tutorials/...
[image]: https://i.stack.imgur.com/uTnEP.png

Answer 3 links:
http://matplotlib.org/users/customizing....

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #matplotlib

#avk47



ACCEPTED ANSWER

Score 681


Use:

import matplotlib.pyplot as plt

plt.gcf().subplots_adjust(bottom=0.15)

# alternate option without .gcf
plt.subplots_adjust(bottom=0.15)

to make room for the label, where plt.gcf() means get the current figure. plt.gca(), which gets the current Axes, can also be used.

Edit:

Since I gave the answer, matplotlib has added the plt.tight_layout() function.

See matplotlib Tutorials: Tight Layout Guide

So I suggest using it:

fig, axes = plt.subplots(ncols=2, nrows=2, figsize=(8, 6))
axes = axes.flatten()

for ax in axes:
    ax.set_ylabel(r'$\ln\left(\frac{x_a-x_b}{x_a-x_c}\right)$')
    ax.set_xlabel(r'$\ln\left(\frac{x_a-x_d}{x_a-x_e}\right)$')

plt.tight_layout()
plt.show()

enter image description here




ANSWER 2

Score 349


In case you want to store it to a file, you solve it using bbox_inches="tight" argument:

plt.savefig('myfile.png', bbox_inches="tight")



ANSWER 3

Score 205


An easy option is to configure matplotlib to automatically adjust the plot size. It works perfectly for me and I'm not sure why it's not activated by default.

Method 1

Set this in your matplotlibrc file

figure.autolayout : True

See here for more information on customizing the matplotlibrc file: http://matplotlib.org/users/customizing.html

Method 2

Update the rcParams during runtime like this

from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})

The advantage of using this approach is that your code will produce the same graphs on differently-configured machines.




ANSWER 4

Score 10


plt.autoscale() worked for me.