2016-04-28 112 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需要弧度。所以你需要做的就是以弧度進行角度測量。