2017-04-12 121 views
0

當我繪製我的半小時時間序列,我的軸標籤是奇數(如16:33:12h左右......) 當我使用HourLocator修復此問題時(16:33h - > 16:00h),然後我的x標籤完全消失。matplotlib HourLocator竊取我的x標籤

我的代碼是:

from datetime import date, timedelta, datetime, time 
from matplotlib.dates import DayLocator, HourLocator 
import matplotlib.pyplot as plt 

start = time(0, 0, 0) 
delta = timedelta(minutes=30) 
times = [] 

for i in range(len(day_load)): 
    dt = datetime.combine(date.today(), time(0, 0)) + delta * i 
    times.append(dt.time()) 

load = [i/48 for i in range(48)] 

fig, ax = plt.subplots() 
ax.plot_date(times, load) 
ax.xaxis.set_major_locator(HourLocator()) 
plt.show() 

我如何能實現「即使」標籤(在最佳實踐方式 - 我不想再重寫每隔陰謀代碼)。 當我評論倒數第二行,我得到正常的「奇」的標籤:(

謝謝解答!

回答

0

有是兩個主要問題:

  • 您需要使用完整的日期時間對象,而不僅僅是時間。因此,您應該直接附加dt而不是dt.time()
  • 你不僅需要一個定位器,而且還需要一個格式化器來產生好的標籤。在這裏您可以使用DateFormatter("%H:%M")來顯示小時和分鐘。

完整代碼:

from datetime import date, timedelta, datetime, time 
from matplotlib.dates import DayLocator, HourLocator,DateFormatter 
import matplotlib.pyplot as plt 

start = time(0, 0, 0) 
delta = timedelta(minutes=30) 
times = [] 
n=48 

for i in range(n): 
    # use complete datetime object, not only time 
    dt = datetime.combine(date.today(), time(0, 0)) + delta * i 
    times.append(dt) 

load = [i/float(n) for i in range(n)] 

fig, ax = plt.subplots() 
ax.plot_date(times, load) 

# set a locator, as well as a formatter 
ax.xaxis.set_major_locator(HourLocator()) 
ax.xaxis.set_major_formatter(DateFormatter("%H:%M")) 

#optionally rotate the labels and make more space for them 
fig.autofmt_xdate() 
plt.show() 

enter image description here

0

你的代碼不能運行,因爲day_load是不確定的,我也得到其他一些問題。

不是一個答案,但我認爲你是使用pandas的好。它可以很容易地創建一個date_range,並繪製被處理得很好,無需調整。

from scipy import stats 
import pandas as pd 

n = 20 
index = pd.date_range(start = '2016-01-01', periods = n, freq='1H') 
df = pd.DataFrame(index = index) 
df["value"] = stats.norm().rvs(n) 

df.plot()