如何在极坐标 Matplotlib 图中(楔形图)围绕 0(两侧)设置限制

How to set limits around (on both sides of) 0, in a polar Matplotlib plot (wedge diagram)

我正在制作楔形图(在 space 中绘制类星体,RA 为 theta,Dec 为 r)。我需要在 0 的两侧设置极坐标图的限制。我的限制应该从 45 度到 315 度,这两个值之间有 0 度 (45-0-315)。我该怎么做?

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt

theta = (np.pi/180)*np.array([340.555906,3.592373,32.473440,33.171584,35.463857,44.268397,339.362504,345.211906,346.485567,346.811945,348.672405,349.180736,349.370850,353.098343])
r = np.array([-32.906663,-33.842402,-32.425917,-32.677975, -30.701083,-31.460307,-32.909861,-30.802969,-33.683759,-32.207783,-33.068686,-33.820102,-31.438195,-31.920375])

colors = 'red'

fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
c = ax.scatter(theta, r, c=colors, cmap='hsv', alpha=0.75)

plt.show()

如果我设置限制:

ax.set_thetamin(45)
ax.set_thetamax(-45)

我得到了正确的图表切片,但 theta 轴上的值错误(该轴现在从 -45-45 度)。

如果我设置限制:

ax.set_thetamin(45)
ax.set_thetamax(315)

我得到了错误的图表切片,但是 theta 轴上的值是正确的。

怎么办?

如果 thetaminthetamax 有正负值,matplotlib 似乎只会使 theta 限制跨越 theta=0。来自 set_thetalim():

的文档字符串

Values are wrapped in to the range [0, 2π] (in radians), so for example it is possible to do set_thetalim(-np.pi / 2, np.pi / 2) to have an axes symmetric around 0.

所以设置:

ax.set_thetamin(45)
ax.set_thetamax(-45)

是获得你想要的情节的正确做法。然后我们可以稍后使用 ticker.FuncFormatter 修改刻度以获得您想要的刻度值。

例如:

import matplotlib.ticker as ticker

fmt = lambda x, pos: "{:g}".format(np.degrees(x if x >= 0 else x + 2 * np.pi))
ax.xaxis.set_major_formatter(ticker.FuncFormatter(fmt))

产生:

为了完整起见,我将它们全部放在您的脚本中:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

theta = (np.pi/180)*np.array([340.555906,3.592373,32.473440,33.171584,35.463857,44.268397,339.362504,345.211906,346.485567,346.811945,348.672405,349.180736,349.370850,353.098343])
r = np.array([-32.906663,-33.842402,-32.425917,-32.677975, -30.701083,-31.460307,-32.909861,-30.802969,-33.683759,-32.207783,-33.068686,-33.820102,-31.438195,-31.920375])

colors = 'red'

fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
c = ax.scatter(theta, r, c=colors, cmap='hsv', alpha=0.75)

ax.set_thetamin(45)
ax.set_thetamax(-45)

fmt = lambda x, pos: "{:g}".format(np.degrees(x if x >= 0 else x + 2 * np.pi))
ax.xaxis.set_major_formatter(ticker.FuncFormatter(fmt))

plt.show()