2017-07-06 22 views
0

在Jupyter筆記本中繪製具有不同時間分辨率(小時,每日,每月)的3只大熊貓數據框時,我想對所有三個子圖應用一致的格式,僅顯示月份而不顯示年份即1月,2月,3月,而不是2010年1月,2010年2月,2010年3月)。對Jupyter筆記本中的所有子圖應用格式化

問題:如何在所有子圖上應用格式?

導入庫

import matplotlib 
import matplotlib.dates 
import matplotlib.pyplot as plt 
import numpy as np 
import os 
import pandas as pd 
import seaborn as sns 
%matplotlib inline 

創建3個dataframes

hourly = pd.DataFrame({'val': np.random.rand(24*365)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1H')) 
daily = pd.DataFrame({'val': np.random.rand(365)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1D')) 
monthly = pd.DataFrame({'val': np.random.rand(12)}, index=pd.date_range('2010-01-01', '2010-12-31 23:00', freq='1M')) 

劇情和應用格式到三個副區

def plot2(hourly, daily, monthly): 
    f, ax = plt.subplots(3, 1, sharex = False, figsize=(16, 14)) 
    hourly[['val']].plot(ax=ax[0], legend=False) 
    daily[['val']].plot(ax=ax[1], legend=False) 
    monthly[['val']].plot(ax=ax[2], legend=False) 

    for axA in ax: 
     month = matplotlib.dates.MonthLocator() 
     monthFmt = matplotlib.dates.DateFormatter('%b') 
     axA.xaxis.set_major_locator(month) 
     axA.xaxis.set_major_formatter(monthFmt) 
     for item in axA.get_xticklabels(): 
      item.set_rotation(0) 

    sns.despine() 
    plt.tight_layout() 
    return f, ax 

plot2(hourly, daily, monthly) 

所得圖顯示了所希望的格式的第二和第三圖,但不是第一個情節。 Figure showing the first plot is not formatted properly, but the second and third plots are formatted properly

我使用Python 3.5

回答

0

好像大熊貓有一些問題。使用matplolib直接效果更好:

def plot2(hourly, daily, monthly): 
    f, ax = plt.subplots(3, 1, sharex = False, figsize=(16, 14)) 
    ax[0].plot(hourly.index, hourly[['val']]) 
    ax[1].plot(daily.index, daily[['val']]) 
    ax[2].plot(monthly.index, monthly[['val']]) 

    for axA in ax[::-1]: 
     month = matplotlib.dates.MonthLocator() 
     monthFmt = matplotlib.dates.DateFormatter('%b') 
     axA.xaxis.set_major_locator(month) 
     axA.xaxis.set_major_formatter(monthFmt) 
     for item in axA.get_xticklabels(): 
      item.set_rotation(0) 

    sns.despine() 
    plt.tight_layout() 
    return f, ax 

enter image description here

+0

由於沒有特殊的格式,這個數字仍顯示2010年1月在所有三個次要情節。對於這個應用程序,我只想顯示月份而不顯示年份。 – GNguyen

+0

現在應該會更好。 –