You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一figure中创建两个独立的极坐标subplot?

解决极坐标子图重叠的问题

嘿,你遇到的问题根源很简单——你两次调用了plt.subplot(111),这个参数的格式是行数列数位置,111代表1行1列的第1个子图,所以两次调用其实是在同一个坐标轴上绘图,自然就把两个曲线叠在一起啦!

下面给你两种修改方案,都能实现同一画布中两个独立的极坐标子图:

方案1:用plt.subplots一次性创建(推荐)

这种方式更简洁,能直接获取所有子图对象,代码可读性更高:

import numpy as np
import matplotlib.pyplot as plt

def GenerateTrigonometryTable(x):
    #Define Function
    A = np.arange(0, 360, x)
    B = np.sin(A*np.pi/180)
    C = np.cos(A*np.pi/180)
    table = np.dstack(([A],[B],[C]))
    return table

Theta = GenerateTrigonometryTable(5)[:,:,0]
STheta = GenerateTrigonometryTable(5)[:,:,1]
CTheta = GenerateTrigonometryTable(5)[:,:,2]

# 创建1行2列的画布,所有子图启用极坐标投影
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, subplot_kw={'projection': 'polar'})

# 在第一个子图绘制正弦曲线
ax1.plot(Theta.flatten(), STheta.flatten())
ax1.set_title('Sin(θ)')  # 添加标题区分两个子图

# 在第二个子图绘制余弦曲线
ax2.plot(Theta.flatten(), CTheta.flatten())
ax2.set_title('Cos(θ)')

plt.tight_layout()  # 自动调整子图间距,避免标题和坐标轴重叠
plt.show()

方案2:用plt.subplot逐个创建

如果你更习惯单独创建子图,只需要把111改成对应的位置参数即可:

import numpy as np
import matplotlib.pyplot as plt

def GenerateTrigonometryTable(x):
    #Define Function
    A = np.arange(0, 360, x)
    B = np.sin(A*np.pi/180)
    C = np.cos(A*np.pi/180)
    table = np.dstack(([A],[B],[C]))
    return table

Theta = GenerateTrigonometryTable(5)[:,:,0]
STheta = GenerateTrigonometryTable(5)[:,:,1]
CTheta = GenerateTrigonometryTable(5)[:,:,2]

fig = plt.figure()

# 1行2列的第1个子图,启用极坐标
ax1 = plt.subplot(121, projection='polar')
ax1.plot(Theta.flatten(), STheta.flatten())

# 1行2列的第2个子图,启用极坐标
ax2 = plt.subplot(122, projection='polar')
ax2.plot(Theta.flatten(), CTheta.flatten())

plt.tight_layout()
plt.show()

关键说明

  • subplot的参数格式是abc:a是行数,b是列数,c是当前子图的位置(从左到右、从上到下计数)。比如121就是1行2列布局里的第1个位置,122是第2个位置。
  • 两种方案都确保了ax1和ax2是完全独立的坐标轴对象,绘图时不会互相干扰。

内容的提问来源于stack exchange,提问作者JCrispy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:20:13