2016-10-13 24 views
0

私は、熱量摂取の簡単な時系列解析のためにpythonを使用しています。私は、時系列上の時系列とローリング平均/標準偏差をプロットしています。ここでenter image description here2番目のy軸と重複したラベル付け?

私はそれを行う方法である:それはこのようになります

## packages & libraries 
import pandas as pd 
import numpy as np 
import matplotlib.pylab as plt 
from pandas import Series, DataFrame, Panel 


## import data and set time series structure 
data = pd.read_csv('time_series_calories.csv', parse_dates={'dates': ['year','month','day']}, index_col=0) 


## check ts for stationarity 

from statsmodels.tsa.stattools import adfuller 
def test_stationarity(timeseries): 

    #Determing rolling statistics 
    rolmean = pd.rolling_mean(timeseries, window=14) 
    rolstd = pd.rolling_std(timeseries, window=14) 

    #Plot rolling statistics: 
    orig = plt.plot(timeseries, color='blue',label='Original') 
    mean = plt.plot(rolmean, color='red', label='Rolling Mean') 
    std = plt.plot(rolstd, color='black', label = 'Rolling Std') 
    plt.legend(loc='best') 
    plt.title('Rolling Mean & Standard Deviation') 
    plt.show() 

プロットは良い見ていない - ローリングSTDは、変動の規模を歪め、x軸ラベルをめちゃくちゃにされているので。私は2つの疑問を持っています:(1)どのようにして、ローリングスタンダードをセコイy軸上にプロットできますか? (2)x軸に重複したラベル付けを修正するにはどうすればよいですか?あなたの助けを借りて

EDIT

私は次のことを得ることができた: enter image description here

しかし、私は伝説が整理できますか?

+1

「Rolling Std」の凡例を作成するとき(または両方の凡例に対して)、「frameon = False」を入力するとハッキリに伝わることがあります。 –

答えて

1

1)ax2 = ax1.twinx()で2番目の(ツイン)軸を作ることができます。here for an exampleを参照してください。これはあなたが必要とするものですか?

2)この質問には、古い質問がいくつかあると思います。つまり、here,herehereです。提供されたリンクによれば、最も簡単な方法はおそらくplt.xticks(rotation=70)またはplt.setp(ax.xaxis.get_majorticklabels(), rotation=70)またはfig.autofmt_xdate()のいずれかを使用することです。私の愚かで

ax1.plot(something, 'r--') # one plot into ax1 
ax2.plot(something else, 'gx') # another into ax2 

# create two empty plots into ax1 
ax1.plot([][], 'r--', label='Line 1 from ax1') # empty fake-plot with same lines/markers as first line you want to put in legend 
ax1.plot([][], 'gx', label='Line 2 from ax2') # empty fake-plot as line 2 
ax1.legend() 

:1つの伝説に異なる軸の間に線を共有する場合回答が を編集する

import matplotlib.pyplot as plt 
fig, ax = plt.subplots() 
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]) 
plt.xticks(rotation=70) # Either this 
ax.set_xticks([1, 2, 3, 4, 5]) 
ax.set_xticklabels(['aaaaaaaaaaaaaaaa','bbbbbbbbbbbbbbbbbb','cccccccccccccccccc','ddddddddddddddddddd','eeeeeeeeeeeeeeeeee']) 
# fig.autofmt_xdate() # or this 
# plt.setp(ax.xaxis.get_majorticklabels(), rotation=70) # or this works 
fig.tight_layout() 
plt.show() 

はあなたに伝説を持つようにしたい軸に、いくつかの偽のプロットを作成することですたとえばax1の元のプロットにラベルを付けるほうがよいでしょうが、あなたがその考えを得ることを願っています。重要なことは、元のプロットと同じ線とマーカーの設定で「凡例プロット」を作成することです。プロットするデータがないため、擬似プロットはプロットされません。

+0

ありがとうございます!それはすでに私にかなり役立ちます。ローリングスタンダードのための第2のy軸を取得する方法に関する任意のアイデア? – Rachel

+0

私はその質問に答えるのを忘れていたことに気付きました。更新された回答をご覧ください。 – pathoren

+0

ありがとう、それはすでに本当にうまくいきます!しかし、どのように伝説を組み合わせるのですか? (OPの編集写真を参照) – Rachel

関連する問題