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

标签 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()

结果是这张图:

polar plot 你可以清楚地看到

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

(b) 轴标签位置是固定的。我希望轴标签也与刻度标签一起移动。即在左边的图中,“theta”应该在右边,而在右边的图中“r”应该在上面。

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

最佳答案

我认为最重要的一点是弄清楚左、右、下、上的常用概念如何在 matplotlib 中转换为极轴。

enter image description here

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

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

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

对于上面显示的情况。

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

完整的示例代码:

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()

enter image description here

关于python - matplotlib 极坐标图刻度/轴标签位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55503584/

相关文章:

python - 如何提取存储在 mock.call 中的参数

python - 将 rgb 代码列表转换为 matplotlib 颜色图

python - 如何在 3D hist python/matplotlib 中自定义轴

python - Pandas 中 pd.plotting.register_matplotlib_converters() 有什么用

python - 如何向公众发布使用 API key 的 Python 应用程序?

python - 按钮在 pycharm 中使用 python 和 tkinter 在新窗口中打开主页的重复窗口

python - Apache2 + RewriteMap + Python——返回 'NULL' 时,apache 挂起

python - 将带有数字数组的嵌套字典保存到 CSV 文件中

Python 绘图库

python - 如何在 matplotlib 中添加悬停注释