How do I extend the margin at the bottom of a figure in Matplotlib?

坚强是说给别人听的谎言 提交于 2021-01-16 12:30:31

问题


The following screenshot shows my x-axis.

enter image description here

I added some labels and rotated them by 90 degrees in order to better read them. However, pyplot truncates the bottom such that I'm not able to completely read the labels. How do I extend the bottom margin in order to see the complete labels?


回答1:


Two retroactive ways:

fig, ax = plt.subplots()
# ...
fig.tight_layout()

Or

fig.subplots_adjust(bottom=0.2) # or whatever

Here's a subplots_adjust example: http://matplotlib.org/examples/pylab_examples/subplots_adjust.html

(but I prefer tight_layout)




回答2:


A quick one-line solution that has worked for me is to use pyplot's auto tight_layout method directly, available in Matplotlib v1.1 onwards:

plt.tight_layout()

This can be invoked immediately before you show the plot (plt.show()), but after your manipulations on the axes (e.g. ticklabel rotations, etc).

This convenience method avoids manipulating individual figures of subplots.

Where plt is the standard pyplot from: import matplotlib.pyplot as plt




回答3:


fig.savefig('name.png', bbox_inches='tight')

works best for me, since it doesn't reduce the plot size compared to

fig.tight_layout()



回答4:


Subplot-adjust did not work for me, since the whole figure would just resize with the labels still out of bounds.

A workaround I found was to keep the y-axis always a certain margin over the highest or minimum y-values:

x1,x2,y1,y2 = plt.axis()
plt.axis((x1,x2,y1 - 100 ,y2 + 100))


来源:https://stackoverflow.com/questions/27878217/how-do-i-extend-the-margin-at-the-bottom-of-a-figure-in-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!