2014-10-04 3 views
1

나는 pandas 시리즈로 나에게 사용할 수있는 분 재고 데이터로 분필을 그리려고합니다. 재고 데이터는 오전 9시 30 분에서 오후 4시 사이에 제공됩니다. 음모를 꾸미면 다음과 같은 결과가 나옵니다. time seriestimeseries 플로팅

여가 시간에 보간을 피할 수있는 방법이 있습니까?

+1

이 바로 그 두 점 사이에 선을 그립니다하기 matplotlib, 보간하지 않습니다. 이를 극복하기 위해이 두 점 사이에 최소한 하나의 NaN이 있어야합니다. 예를 들어'df.resample ('1min') '으로 달성 할 수 있습니다. – joris

+0

예, 재 샘플에서는 두 점 사이에 더 이상 선이 없습니다. 그러나 여전히 빈 공간이 많이 있습니다. 그것을 건너 뛸 수있는 방법이 있습니까? 즉, 하루 중 16:00 이후에 다음 날 09:30을 바로 건너 뛸 수 있습니까? – vdesai

답변

1

마켓이 닫힌 기간을 제외하는 플롯의 축을 직접 구성해야합니다. 이것은 피칭입니다. 예는 다음과 같습니다

import pandas as pd 
import matplotlib.pyplot as plt 
import calendar 
from matplotlib.ticker import FixedLocator 

# --- let's fake up some data: 
drng = pd.period_range('2015-04-01 00:00', '2015-04-02 23:59', freq='1min') 
df = pd.DataFrame({'data':np.random.randn(len(drng))}, index=drng) 
df['data'] = df.data.cumsum() 
# let's only keep the fake data for when the market is open 
# market opens at 9.30am and closes at 4pm. 
df = df[((df.index.hour >= 10) | 
     ((df.index.hour == 9) & (df.index.minute >= 30))) & 
     (df.index.hour <= 15)] 

# --- we will need to construct our own index and labels for matplotlib 
#  this is fiddly ... and will vary depending on period being plotted 
#  this works for two days of data ... but you will want to vary for 
#  shorter or longer periods ... 
df['year'] = df.index.year 
df['month'] = pd.Series(df.index.month, index=df.index 
    ).apply(lambda x: calendar.month_abbr[x]) 
df['day'] = df.index.day 
df['hour'] = df.index.hour 
df['minute'] = df.index.minute 
df.index = range(len(df)) 

minorticks = df[df['minute'] == 0].index.tolist() # hours 
majorticks = df[df['day'] != df['day'].shift()].index.tolist() # days 

minorlabels = pd.Series(df.loc[minorticks, 'hour'].astype(str)).tolist() 
majorlabels = pd.Series('\n' + df.loc[majorticks, 'day'].astype(str) + ' ' + 
       df.loc[majorticks, 'month'].astype(str) + ' ' + 
       df.loc[majorticks, 'year'].astype(str)).tolist() 

# --- and plot 
(fig, ax) = plt.subplots(figsize=(8, 4)) 
df['data'].plot(ax = ax) 
ax.xaxis.set_major_locator(FixedLocator(majorticks)) 
ax.xaxis.set_minor_locator(FixedLocator(minorticks)) 
ax.set_xticklabels(minorlabels, minor=True) 
ax.set_xticklabels(majorlabels, minor=False) 
ax.set_xlabel('Time and Date') 
ax.set_ylabel('Index') 
fig.suptitle('Fake Market Data - without closed time periods') 
fig.tight_layout(pad=2) 
plt.show() 

Example solution for a two-day plot