2016-04-28 128 views
2

我想用this answer风格的Python中的matplotlib以时钟方式绘制数据。绘制我的数据时,我注意到奇怪的行为;数据点具有正确的y值,但不会出现在正确的x值,即时间。我首先想到我的数据是错误的,但是通过以下工作示例重新创建我的问题时,我得出的结论是错误必须在其他地方。用matplotlib Python极性时钟式阴谋

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

这将导致以下情节: enter image description here

我本来期望的是,点的x值排队与时间,考虑equals定义。它目前被定义为一个角度,但我也尝试将其定义为一个小时。为什么不是这样,我怎样才能让我的数据与相应的时间保持一致?

回答

3

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

这将产生以下画面:

enter image description here

或者,你可能会改变你的平等的定义产生来讲角度弧度:equals = np.linspace(0, 2*np.pi, 24, endpoint=False)

+0

谢谢,这解决了我的问题!对于那些有兴趣的人来说,将时间从24小时转换为辐射,只需将时间乘以15即可获得度数,然后将其转换为弧度(尽管肯定有更直接的解决方案)。 'lambda t:np.deg2rad(t * 15)' – Alarik

1

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