jupyter中subplots_adjust调整子图大小无效、子图溢出和日期标签遮挡坐标轴刻度的问题解决
解决在jupyter中使用subplots_adjust()调整无效的问题
subplots_adjust()可以用于调整子图与figure层之间的距离,比如在figure内有多个坐标轴ax1、ax2、ax3…,用subplots_adjust()可以调整所有figure与所有子图(绘图区)的距离,也可以调整子图与子图之间的距离。
但是在使用了subplots_adjust()之后,jupyter中通常看不出来变化,但是使用savefig()之后又能输出具有正确距离的图片。
在IPython的文档中给出了答案。
The default for inline figures sets bbox_inches to ‘tight’. This can cause discrepancies between the displayed image and the identical image created using savefig. This behavior can be disabled using the %config magic:
In [3]: %config InlineBackend.print_figure_kwargs = {‘bbox_inches’:None}
简单说就是在使用matplotlib的inline模式显示时,默认的bbox_inches设置为’tight’,所以无论我们怎么设置subplots_adjust(),结果都是只显示存在坐标轴的绘图区,而不是这个figure层。
如果我们需要完整显示整个figure层,则需要在开头添加魔法函数:
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
以下举例说明
举例来自matplotlib的example,为了更好的显示figure的位置,我们为figure层添加一个红色边框:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ["SimHei"] #配置中文
plt.rcParams['axes.unicode_minus'] = False #配置负号显示
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
men_std = [2, 3, 4, 1, 2]
women_std = [3, 5, 2, 3, 3]
width = 0.35 # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots(figsize=(16,9))
fig.set_edgecolor('red') # 给figure层添加一个红色边框,便于观察。
fig.set_linewidth(5)
# fig.subplots_adjust(left=0, right=0.5, bottom=0, top=0.5) #设置子图大小和范围
ax.bar(labels, men_means, width, yerr=men_std, label='Men')
ax.bar(labels, women_means, width, yerr=women_std, bottom=men_means,
label='Women')
ax.set_ylabel('Scores')
ax.set_xlabel('x轴标签',labelpad=5) #添加一个x标签,间距为5
ax.set_title('Scores by group and gender')
ax.legend()
plt.show()
输出为:
当我们通过:
fig.subplots_adjust(left=0., right=0.5, bottom=0, top=0.5)
将绘图区(也就是ax所处的位置)压缩到figure层的左下角1/4位置的时候,我们期待得到的结果应该是这样的(下图由fig.savefig()直接保存为文件):
但是我们在jupyter中看到的却没有任何变化的,如下图:
当我们添加了一行魔法函数:
%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
我们在jupyter就能看到同直接导出文件一样的结果了:
在这里我们发现x、y轴的刻度和标签都因为超出figure层而看不见了,那我们可以适当调整我们可以通过调整subplots_adjust()的几个参数实现图像的显示完全,有6个参数,取值均为0~1,figure层左下角为(0,0),右上角为(1,1):
- left、right、bottom、top分别为子图的左、右、底、上界,因此right和top必须大于left和bottom。
- wspace、hspace分别调整多个子图之间横向间距和纵向间距。
subplots_adjust()调整的对象是Figure实例,也就是本例中的fig,而不是ax。所以在面向对象写法中调用方法是fig.subplots_adjust()。该方法限制的是fig内所有子图的显示范围,而不是某一个子图。有一点点像CSS中的padding值,但这里是保持fig盒子不变,而挤压fig的内容。
另外有时候我们的横坐标刻度是比较长的日期,在旋转45°之后可能会跟x轴标签(xlabel)产生重叠
调整xlabel与刻度之间的距离,labelpad越大则x标签距离刻度越远。
ax.set_xlabel('x标签名称',labelpad=5) #ax是指定的某一个子图
举例:
- labelpad=0
- labelpad=50