https://space.bilibili.com/523606542
在一个Figure
上面,可能存在多个Axes
对象,如果Figure
比较小,那么有可能会造成一些图形元素重叠,这时候我们就可以通过fig.tight_layout
或者是fig.subplots_adjust
方法来帮我们调整。假如现在没有经过调整,那么以下代码的效果图如下:
import matplotlib.pyplot as plt
import numpy as np
def example_plot(ax, fontsize=12):
ax.plot([1, 2])
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
fig,axes = plt.subplots(2,2)
fig.set_facecolor("y")
example_plot(axes[0,0])
example_plot(axes[0,1])
example_plot(axes[1,0])
example_plot(axes[1,1])
效果图如下:
为了避免多个图重叠,可以使用plt.tight_layout来实现:
# 之前的代码...
plt.tight_layout()
效果图如下:
其中tight_layout还有两个参数可以使用,分别是w_pad和h_pad,这两个参数分别表示的意思是在水平方向的图之间的间距,以及在垂直方向这些图的间距。
另外也可以通过fig.subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)来实现,效果如下:
# 之前的代码...
fig.subplots_adjust(0,0,1,1,hspace=0.5,wspace=0.5)
效果图如下:
如果布局不是固定的几宫格的方式,而是某个图占据了多行或者多列,那么就需要采用一些手段来实现。如果不是很复杂,那么直接可以通过subplot
等方法来实现。示例代码如下:
ax1 = plt.subplot(221)
ax2 = plt.subplot(223)
ax3 = plt.subplot(122)
效果图如下:
但是如果实现的布局比较复杂,那么就需要采用GridSpec对象来实现。示例代码如下:
fig = plt.figure()
# 创建3行3列的GridSpec对象
gs = fig.add_gridspec(3,3)
ax1 = fig.add_subplot(gs[0,0:3])
ax1.set_title("[0,0:3]")
ax2 = fig.add_subplot(gs[1,0:2])
ax2.set_title("[1,0:2]")
ax3 = fig.add_subplot(gs[1:3,2])
ax3.set_title("[1:3,2]")
ax4 = fig.add_subplot(gs[2,0])
ax4.set_title("[2,0]")
ax5 = fig.add_subplot(gs[2,1])
ax5.set_title("[2,1]")
plt.tight_layout()
效果图如下:
也可以设置宽高比例。示例代码如下:
# 设置宽度比例为1:2:1
widths = (1,2,1)
# 设置高度比例为2:2:1
heights = (2,2,1)
fig = plt.figure()
# 创建GridSpec对象的时候指定宽高的比
gs = fig.add_gridspec(3,3,width_ratios=widths,height_ratios=heights)
for row in range(0,3):
for col in range(0,3):
fig.add_subplot(gs[row,col])
plt.tight_layout()
效果图如下:
通过fig.add_axes
的方式添加Axes
对象,可以直接指定位置。也可以在添加完成后,通过axes.set_position
的方式设置位置。示例代码如下:
# add_axes的方式
fig = plt.figure()
fig.add_subplot(111)
fig.add_axes([0.2,0.2,0.4,0.4])
# 设置position的方式
fig,axes = plt.subplots(1,2)
axes[1].set_position([0.2,0.2,0.4,0.4])
fig = plt.figure(figsize=(8,8))
widths = (2,0.5)
heights = (0.5,2)
gs = fig.add_gridspec(2,2,width_ratios=widths,height_ratios=heights)
# 顶部的直方图
ax1 = fig.add_subplot(gs[0,0])
ax1.hist(male_athletes['Height'],bins=20)
for tick in ax1.xaxis.get_major_ticks():
tick.label1On = False
# 中间的散点图
ax2 = fig.add_subplot(gs[1,0])
ax2.scatter('Height','Weight',data=male_athletes)
# 右边的直方图
ax3 = fig.add_subplot(gs[1,1])
ax3.hist(male_athletes['Weight'],bins=20,orientation='horizontal')
for tick in ax3.yaxis.get_major_ticks():
tick.label1On = False
fig.tight_layout(h_pad=0,w_pad=0)
效果图如下: