Python 使用 matplotlib 的类似极地时钟的绘图

Python polar clock-like plot with matplotlib

我正在尝试使用 Python 中的 matplotlib 以 this answer 的风格以顺时针方式绘制数据。我在绘制数据时注意到奇怪的行为;数据点具有正确的 y 值,但不会出现在正确的 x 值处,即时间。我首先认为我的数据有误,但在使用以下工作示例重现我的问题后,我得出的结论是错误一定出在其他地方。

import numpy as np
import matplotlib.pyplot as plt     

ax = plt.subplot(111, polar=True)
equals = np.linspace(0, 360, 24, endpoint=False) #np.arange(24)
ones = np.ones(24)
ax.scatter(equals, ones)       

# Set the circumference labels
ax.set_xticks(np.linspace(0, 2*np.pi, 24, endpoint=False))
ax.set_xticklabels(range(24))      

# Make the labels go clockwise
ax.set_theta_direction(-1)       

# Place 0 at the top
ax.set_theta_offset(np.pi/2.0)       

plt.show()

结果如下图:

考虑到 equals 的定义,我预计点的 x 值与小时数一致。它目前被定义为一个角度,但我也尝试将其定义为一个小时。为什么不是这样,我怎样才能让我的数据与相应的时间对齐?

Matplotlib 期望角度以弧度而不是度为单位(参见 open bug report)。您可以使用 numpy 函数 np.deg2rad 转换为弧度:

import numpy as np
import matplotlib.pyplot as plt     

ax = plt.subplot(111, polar=True)
equals = np.linspace(0, 360, 24, endpoint=False) #np.arange(24)
ones = np.ones(24)
ax.scatter(np.deg2rad(equals), ones)       

# Set the circumference labels
ax.set_xticks(np.linspace(0, 2*np.pi, 24, endpoint=False))
ax.set_xticklabels(range(24))      

# Make the labels go clockwise
ax.set_theta_direction(-1)       

# Place 0 at the top
ax.set_theta_offset(np.pi/2.0)       

plt.show()

这会产生下图:

或者,您可以更改 equals 的定义以根据弧度生成角度:equals = np.linspace(0, 2*np.pi, 24, endpoint=False)

您的 equals 数组以度为单位,但 matplotlib 需要弧度。因此,您需要做的就是以弧度为单位进行角度测量。