matplotlib 极坐标图刻度/轴标签位置

Han*_*nah 5 python matplotlib

我一直在寻找一种方法来可靠地定位极坐标图中的刻度和轴标签。请看下面的例子:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=[10, 5])
ax0 = fig.add_axes([0.05, 0.05, 0.4, 0.9], projection="polar")
ax1 = fig.add_axes([0.55, 0.05, 0.4, 0.9], projection="polar")

r0 = np.linspace(10, 12, 10)
theta0 = np.linspace(0, 0.1, 10)

ax0.quiver(theta0, r0, -0.1, 0.1)
ax1.quiver(theta0 + np.pi, r0, -0.1, 0.1)

ax0.set_thetamin(-2)
ax0.set_thetamax(10)

ax1.set_thetamin(178)
ax1.set_thetamax(190)

for ax in [ax0, ax1]:

    # Labels
    ax.set_xlabel("r")
    ax.set_ylabel(r"$\theta$", labelpad=10)

    # R range
    ax.set_rorigin(0)
    ax.set_rmin(9)
    ax.set_rmax(13)

plt.show()
Run Code Online (Sandbox Code Playgroud)

结果如下图:

极坐标图 你可以清楚地看到

(a) 径向轴上的刻度标签位置在图之间从下到上切换,并且 theta 的刻度标签从右到左切换。

(b) 轴标签位置是固定的。我希望轴标签也随着刻度标签移动。即在左图中,“theta”应位于右侧,而在右图中,“r”应位于顶部。

如何以某种方式控制轴/刻度标签,以便它们正确定位?对于例如 90 度的偏移,情况甚至会变得更糟,因为此时 theta 轴实际上是垂直的,并且刻度标签完全关闭。

Imp*_*est 5

我认为最重要的是要清楚左、右、下、上的常见概念如何转化为 matplotlib 中的极轴。

在此输入图像描述

角度轴是“x”轴。径向轴是“y”轴。“底”是外环。“顶”是内环。“左”是角轴起点处的径向轴,“右”是角轴终点处的径向轴。

然后,这允许像往常一样设置刻度位置,例如

ax.tick_params(labelleft=True, labelright=False,
               labeltop=False, labelbottom=True)
Run Code Online (Sandbox Code Playgroud)

对于上面所示的情况。

x 和 y 标签 ( set_xlabel/ set_ylabel) 未翻译。这里的左、右、上、下指的是笛卡尔定义,就像普通的线性轴一样。这意味着对于某些位置,它们不能用于标记轴,因为它们距离太远。text另一种方法是在所需位置创建一个。

完整的示例代码:

import numpy as np
import matplotlib.pyplot as plt

fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(10,5), 
                               subplot_kw=dict(projection="polar"))

ax0.set(thetamin=180, thetamax=230)
ax1.set(thetamin=  0, thetamax= 50)

plt.setp([ax0, ax1], rorigin=0, rmin=5, rmax=10)

ax0.tick_params(labelleft=False, labelright=True,
                labeltop=True, labelbottom=False)

trans, _ , _ = ax1.get_xaxis_text1_transform(-10)
ax1.text(np.deg2rad(22.5), -0.18, "Theta Label", transform=trans, 
         rotation=22.5-90, ha="center", va="center")


plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述