Stef1611 Asked: 2024-11-05 20:55:05 +0800 CST2024-11-05 20:55:05 +0800 CST 2024-11-05 20:55:05 +0800 CST 如何在 Matplotlib 中用颜色填充子图之间的空格? 772 使用以下代码: nb_vars=4 fig, axs = plt.subplots(4,4,figsize=(8,8), gridspec_kw = {'wspace':0.20, 'hspace':0.20}, dpi= 100) for i_ax in axs: for ii_ax in i_ax: ii_ax.set_yticklabels([]) for i_ax in axs: for ii_ax in i_ax: ii_ax.set_xticklabels([]) 子图之间的空间是白色的。如何给它们上色?用不同的颜色?例如,参见下图: python 1 个回答 Voted Best Answer mozway 2024-11-05T21:30:30+08:002024-11-05T21:30:30+08:00 您可以在轴之间添加补丁: from matplotlib import patches nb_vars=4 # colors between two axes in a row r_colors = [['#CC0000', '#CC0000', '#CC0000'], ['#0293D8', '#0293D8', '#0293D8'], ['#FF8E00', '#FF8E00', '#FF8E00'], ['#ABB402', '#ABB402', '#ABB402'], ] # colors between two axes in a column c_colors = [['#CC0000', '#0293D8', '#FF8E00', '#ABB402'], ['#CC0000', '#0293D8', '#FF8E00', '#ABB402'], ['#CC0000', '#0293D8', '#FF8E00', '#ABB402'], ] fig, axs = plt.subplots(4, 4, figsize=(4, 4), gridspec_kw = {'wspace':0.20, 'hspace':0.20}, dpi= 100) h, w = axs.shape for r, i_ax in enumerate(axs): for c, ii_ax in enumerate(i_ax): ii_ax.set_yticklabels([]) ii_ax.set_xticklabels([]) ii_ax.plot([-r, r], [-c, c]) # plot dummy line for demo bbox = ii_ax.get_position() if r+1 < h: ii_ax.add_patch(patches.Rectangle((bbox.x0, bbox.y0), bbox.width, -0.2, facecolor=c_colors[r][c], zorder=-1, clip_on=False, transform=fig.transFigure, figure=fig )) if c+1 < w: ii_ax.add_patch(patches.Rectangle((bbox.x1, bbox.y0), 0.2, bbox.height, facecolor=r_colors[r][c], zorder=-1, clip_on=False, transform=fig.transFigure, figure=fig )) 输出:
您可以在轴之间添加补丁:
输出: