在Matplotlib中,子图(Subplot)是指在一个图形窗口(figure)中创建的多个绘图区域。调整子图大小是数据可视化中常见的需求,可以优化图表布局、提高可读性或适应特定展示需求。
使用plt.figure()
的figsize
参数可以设置整个图形的大小,这会间接影响子图的大小。
import matplotlib.pyplot as plt
# 创建8英寸宽、6英寸高的图形
plt.figure(figsize=(8, 6))
# 添加子图
ax = plt.subplot(111)
ax.plot([1, 2, 3], [4, 5, 6])
plt.show()
subplots_adjust()
方法可以调整子图之间的间距,从而间接改变子图的显示大小。
plt.figure(figsize=(10, 8))
plt.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9, wspace=0.4, hspace=0.4)
# 创建2x2的子图网格
for i in range(1, 5):
plt.subplot(2, 2, i)
plt.plot([i, i+1, i+2], [i*2, i*2+1, i*2+2])
plt.show()
GridSpec
提供了更灵活的子图布局控制,可以指定子图的位置和大小比例。
import matplotlib.gridspec as gridspec
plt.figure(figsize=(10, 8))
gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2], height_ratios=[2, 1])
ax1 = plt.subplot(gs[0])
ax1.plot([1, 2, 3], [1, 4, 9])
ax2 = plt.subplot(gs[1])
ax2.plot([1, 2, 3], [1, 8, 27])
ax3 = plt.subplot(gs[2])
ax3.plot([1, 2, 3], [2, 4, 6])
ax4 = plt.subplot(gs[3])
ax4.plot([1, 2, 3], [3, 6, 9])
plt.show()
新版本的Matplotlib提供了更直观的布局方式。
fig = plt.figure(figsize=(10, 6))
ax_dict = fig.subplot_mosaic(
[
['left', 'right_top'],
['left', 'right_bottom']
],
# 设置宽度比例
width_ratios=[1, 2]
)
ax_dict['left'].plot([1, 2, 3], [1, 2, 3])
ax_dict['right_top'].plot([1, 2, 3], [1, 4, 9])
ax_dict['right_bottom'].plot([1, 2, 3], [1, 8, 27])
plt.show()
原因:子图之间的间距不足
解决:调整wspace
和hspace
参数
fig, axs = plt.subplots(2, 2, figsize=(8, 6))
plt.subplots_adjust(wspace=0.5, hspace=0.5)
原因:默认等分空间
解决:使用GridSpec
的width_ratios
和height_ratios
原因:边距设置不当
解决:调整subplots_adjust
的left
, right
, bottom
, top
参数
figsize
),再调整子图布局GridSpec
或subplot_mosaic
没有搜到相关的文章