Matplotlib中子图的坐标轴变换异常问题求助
解决Matplotlib子图坐标轴变换异常的问题
问题根源
异常的核心原因是pyplot.gca().transData的误用:gca()返回的是当前活跃的子图(Axes),在多子图场景中,活跃子图会随操作自动切换。如果用全局的gca()获取变换基准,大概率拿到的不是目标子图的坐标系,导致图形被绘制到错误区域,出现仅最后一个子图显示变换、或其他子图变换后无内容的情况。
正确解决方法
对每个需要应用坐标轴变换的子图,直接使用该子图自身的transData属性作为变换基准,而非全局gca()获取的对象。这样变换是基于目标子图的坐标系进行,不会出现错位。
修正后的代码示例
以你提供的第三个示例为例,修改后可正常显示子图[1,0]的变换效果:
import numpy as np from matplotlib import pyplot, transforms # Example data to display x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) fig, axs = pyplot.subplots(2, 2) axs[0, 0].plot(x, y) axs[0, 0].set_title('Axis [0, 0]') axs[0, 1].plot(x, y, 'tab:orange') axs[0, 1].set_title('Axis [0, 1]') # 直接使用目标子图axs[1,0]的transData作为变换基准 rot = transforms.Affine2D().rotate_deg(90) target_base = axs[1, 0].transData axs[1, 0].plot(x, y, 'tab:green', transform=rot + target_base) axs[1, 0].set_title('Axis [1, 0]') axs[1, 1].plot(x, -y, 'tab:red') axs[1, 1].set_title('Axis [1, 1]') for ax in axs.flat: ax.set(xlabel='x-label', ylabel='y-label') # Hide x labels and tick labels for top plots and y ticks for right plots. for ax in axs.flat: ax.label_outer() pyplot.show()
多子图批量变换示例
如果要给多个子图应用不同变换,只需为每个子图绑定自身的transData:
# 给axs[0,1]添加45度旋转 rot_01 = transforms.Affine2D().rotate_deg(45) axs[0,1].plot(x, y, 'tab:orange', transform=rot_01 + axs[0,1].transData) # 给axs[1,1]添加90度旋转 rot_11 = transforms.Affine2D().rotate_deg(90) axs[1,1].plot(x, -y, 'tab:red', transform=rot_11 + axs[1,1].transData)
总结
多子图场景下,务必绑定目标子图自身的transData作为变换基准,彻底避免全局gca()带来的坐标系错位问题。
内容的提问来源于stack exchange,提问作者ClimateCalamity
相关产品推荐
相关产品推荐

