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

极坐标图顺时针模式下径向文本标注旋转角度异常问题求助

极坐标图修改θ参数后文本旋转异常的解决方法

默认极坐标配置下,在半径上放置文本的代码运行正常:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, polar=True)
ax.set_yticklabels("")
ax.annotate('test',
            xy=(np.deg2rad(90), 0.5),
            fontsize=15,
            rotation=90)
plt.show()

此时文本沿θ=90°对应的正北半径方向正确显示。

但修改θ零点位置为北("N")、θ方向为顺时针(-1)后,文本坐标位置正确,但旋转角度异常:

fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, polar=True)
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
ax.set_yticklabels("")
ax.annotate('test',
            xy=(np.deg2rad(90), 0.5),
            fontsize=15,
            rotation=90)
plt.show()

此时文本并未沿θ=90°对应的正东半径方向对齐,而是保持了固定的绝对90°旋转。

问题原因

annotate的rotation参数是基于屏幕坐标系的绝对角度,而非极坐标的相对角度。修改极坐标的θ零点位置和方向后,极坐标到屏幕坐标的映射关系发生了变化,但rotation仍使用固定值,导致文本旋转与半径方向错位。

解决方案

通过ax.transData.transform_angles函数,将极坐标角度自动转换为屏幕坐标系的绝对角度,以此作为文本旋转值,确保文本始终沿半径方向对齐:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, polar=True)
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
ax.set_yticklabels("")

theta = np.deg2rad(90)
r = 0.5

# 转换极坐标角度为屏幕绝对角度
screen_angle = ax.transData.transform_angles(
    np.array([np.rad2deg(theta)]), 
    np.array([[theta, r]])
)[0]

ax.annotate('test',
            xy=(theta, r),
            fontsize=15,
            rotation=screen_angle)

plt.show()

原理说明

transform_angles会根据当前轴的极坐标配置(零点位置、旋转方向),自动适配极坐标到屏幕坐标的映射规则,计算出文本需要的旋转角度。无论后续如何修改极坐标参数,文本都会始终沿半径方向对齐,无需手动调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 02:46:17