2017-05-08 76 views
1

我試圖用timedelta索引來繪製熊貓數據框中的一些數據,並且想要自定義我的x軸中的時間刻度和標籤。這應該很簡單,但事實證明這是一項艱鉅的工作。使用timedelta索引從熊貓數據框繪圖

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.dates as dates 

## I have a df similar to this 
timestamps = pd.date_range(start="2017-05-08", freq="10T", periods=6*6) 
timedeltas = timestamps - pd.to_datetime("2017-05-08") 
yy = np.random.random((len(timedeltas),10)) 
df = pd.DataFrame(data=yy, index=timedeltas) # Ok, this is what I have 

## Now I want to plot this but I want detailed control of the plot so I use matplotlib instead of df.plot 
fig,axes=plt.subplots() 
axes.plot(df.index.values, df.values) 
#axes.plot_date(df.index, df.values, '-') 

axes.xaxis.set_major_locator(dates.HourLocator(byhour=range(0,24,2))) 
axes.xaxis.set_minor_locator(dates.MinuteLocator(byminute=range(0,24*60,10))) 
axes.xaxis.set_major_formatter(dates.DateFormatter('%H:%M')) 

plt.show() 

正如你所看到的,蜱蟲甚至沒有出現。例如,我如何每兩小時添加一次重要的剔號和標籤,並且每10分鐘添加一次次要的剔號?

回答

0

儘管我不清楚根本問題是什麼,但它似乎與使用的軟件包版本有關。當我用一個較老的python發行版(matplotlib 1.5.1,numpy 1.11.1,pandas 0.18.1和python 2.7.12)運行你的例子時,那麼我得到一個沒有刻度的繪圖,就像你所描述的那樣。

不過,我可以得到一個陰謀以正確的用最近的蟒蛇分佈(matplot 2.0.1,numpy的1.12.1,熊貓0.19.1和python運行下面的代碼蜱

plot with correct ticks

3.6.1)。

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.dates as dates 

timestamps = pd.date_range(start="2017-05-08", freq="10T", periods=6*6) 
timedeltas = timestamps - pd.to_datetime("2017-05-08") 
yy = np.random.random((len(timedeltas),10)) 
df = pd.DataFrame(data=yy, index=timedeltas) 

fig,axes=plt.subplots() 
axes.plot_date(df.index, df.values, '-') 

axes.xaxis.set_major_locator(dates.HourLocator(byhour=range(0,24,2))) 
axes.xaxis.set_minor_locator(dates.MinuteLocator(byminute=range(0,24*60,10))) 
axes.xaxis.set_major_formatter(dates.DateFormatter('%H:%M')) 

plt.show() 
+0

感謝您的檢查。也許你也想看看這個:https://stackoverflow.com/questions/43859823/heatmap-in-which-one-of-the-axis-is-of-timedelta-type – Bella