基于Matplotlib多GridSpec的横竖相邻仪表盘布局实现咨询
解决Matplotlib中GridSpec合并单元格实现复杂布局的问题
嘿,我明白你现在卡在中间布局的部分了——要把右侧的单元格合并成一个跨两行的极坐标图其实很简单,咱们一步步来调整你的代码:
核心思路:用GridSpec切片选中多行/多列
在Matplotlib的GridSpec里,你可以通过切片语法来选中连续的行或列,实现单元格合并的效果。对于你的gs1(2行2列),要让右侧图表跨两行,只需要选中所有行的第2列(索引从0开始),也就是gs1[:, 1]。
修改后的完整代码
下面是调整后的代码,重点修改了中间gs1对应的图表创建部分,同时加入了极坐标图的专属设置:
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec def example_plot(ax, is_polar=False): if is_polar: # 极坐标图的示例绘制 ax.plot([0, 1, 2], [0, 1, 2]) ax.set_title('Polar Plot', fontsize=14) else: ax.plot([1, 2]) ax.set_xlabel('x-label', fontsize=12) ax.set_ylabel('y-label', fontsize=12) ax.set_title('Title', fontsize=14) fig = plt.figure(constrained_layout=True) # 建议开启自动布局,更省心 outer_gs = gridspec.GridSpec(nrows=3, ncols=1, figure=fig, height_ratios=[5,2,2], hspace=0.3) gs0 = gridspec.GridSpecFromSubplotSpec(nrows=3, ncols=1, subplot_spec=outer_gs[0], height_ratios=[1,4,1], hspace=0) gs1 = gridspec.GridSpecFromSubplotSpec(nrows=2, ncols=2, subplot_spec=outer_gs[1], width_ratios=[5,2], wspace=0.2, hspace=0.2) gs2 = gridspec.GridSpecFromSubplotSpec(nrows=1, ncols=5, subplot_spec=outer_gs[2], wspace=0, hspace=0.3) # Top 3 adjacent charts for n in range(3): ax = fig.add_subplot(gs0[n]) example_plot(ax) # Middle bit - 2 vertical plots on left, polar plot spanning both rows on right # 左侧第一行图表 ax_left_top = fig.add_subplot(gs1[0, 0]) example_plot(ax_left_top) # 左侧第二行图表 ax_left_bottom = fig.add_subplot(gs1[1, 0]) example_plot(ax_left_bottom) # 右侧跨两行的极坐标图 ax_polar = fig.add_subplot(gs1[:, 1], projection='polar') example_plot(ax_polar, is_polar=True) # Bottom 5 dials for n in range(5): ax = fig.add_subplot(gs2[n]) example_plot(ax) plt.show()
关键修改点说明
- 单元格合并:
gs1[:, 1]中的:表示选中所有行(这里是2行),1表示选中第2列,这样就把右侧的两个单元格合并成了一个Axes容器,用来放极坐标图。 - 极坐标图设置:创建极坐标Axes时必须指定
projection='polar',否则会生成普通的线性坐标轴。 - 自动布局优化:把
constrained_layout设为True,Matplotlib会自动调整子图的间距和大小,避免标签、标题互相重叠。
这样调整后,你就能得到左侧两个垂直排列的普通图表,右侧一个跨两行的极坐标图的中间布局了,整体仪表盘的结构也会更清晰。
内容的提问来源于stack exchange,提问作者Luthor
相关产品推荐
相关产品推荐

