如何在Matplotlib中调整内嵌极坐标子图的大小与位置
在子图内嵌入极坐标子图并控制大小与位置
你当前的问题出在创建极坐标子图时用了add_subplot(111,polar=True),这会生成一个覆盖整个画布的子图,而非嵌入到目标子图内部。要实现嵌入效果,应该使用matplotlib.axes.Axes.inset_axes()方法,它可以在已有子图内创建新的嵌入子图,并通过参数精确控制位置和大小。
修改后的完整代码
import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec time = np.linspace(0, 10, 1000) height = np.sin(time) score = time**2 + height distribution = np.random.normal(0, 1, len(time)) fig = plt.figure(figsize=(10, 5)) gs = GridSpec(nrows=1, ncols=2) # 创建右侧主图 ax2 = fig.add_subplot(gs[:, 1]) ax2.plot(time, score) # 在ax2内部创建极坐标嵌入子图 # bbox参数格式: [左, 下, 宽, 高],取值范围是0-1(相对父子图的比例) ax3 = ax2.inset_axes([0.05, 0.6, 0.35, 0.35], polar=True) ax3.set_theta_zero_location("N") ax3.plot(0 - 1.5708, 0, 'o', linewidth=2, color="k") # 绘制填充区域 theta1 = np.linspace(-0.48332530310852967-1.5708,0.48332530310852967-1.5708, 100) ax3.fill_between(theta1, -0.1, +0.3, color='r') theta2 = np.linspace(0.48332530310852967-1.5708,1.449975909325589-1.5708, 100) ax3.fill_between(theta2, -0.1, +0.3, color='b') theta3 = np.linspace(1.449975909325589-1.5708,2.4166265155426485-1.5708, 100) ax3.fill_between(theta3, -0.1, +0.3, color='r') theta4 = np.linspace(2.4166265155426485-1.5708,3.3832771217597077-1.5708, 100) ax3.fill_between(theta4, -0.1, +0.3, color='b') theta5 = np.linspace(3.3832771217597077-1.5708,3.870223983066126-1.5708, 100) ax3.fill_between(theta5, -0.1, +0.3, color='g') theta6 = np.linspace(3.870223983066126-1.5708,4.836874589283185-1.5708, 100) ax3.fill_between(theta6, -0.1, +0.3, color='r') theta6 = np.linspace(4.836874589283185-1.5708,5.803525195500244-1.5708, 100) ax3.fill_between(theta6, -0.1, +0.3, color='b') ax3.set_ylim(-10,1) ax3.grid(True) plt.show()
关键说明
inset_axes([left, bottom, width, height], polar=True):其中left和bottom是嵌入子图在父子图中的相对位置(0为最左/最下,1为最右/最上),width和height是嵌入子图的相对尺寸,通过调整这四个值可以精确控制极坐标图的位置和大小。- 原代码中
add_subplot(111,polar=True)会直接覆盖整个画布,替换为inset_axes后就能将极坐标图嵌入到指定子图内部。
效果对比
当前效果:
期望效果(修改后可实现):
内容的提问来源于stack exchange,提问作者Ali AlCapone
相关产品推荐
相关产品推荐

