2016-03-22 20 views
0

私は最初のpythonスクリプトをpandasで作成しようとしています。私は毎月のプロットを作成し、各プロットに速度と方向をプロットして10年の風データ(1分の読み値)を持っています。複数のtimeseriesプロットfrom Pandas Dataframe

入力CSVデータは、次のようになります。

Date,Speed,Dir, 
2014-01-01 00:00:00, 13, 179, 
2014-01-01 00:01:00, 13, 178, 
2014-01-01 00:02:00, 11, 169, 
2014-01-01 00:03:00, 11, 178, 
2014-01-01 00:04:00, 11, 181, 

これまでのところ、私は以下の書かれている、これは日付の範囲内に設定月のプロットを作成します。私は、x軸のラベルを修正する必要があることを除いて、このプロットがどのように見えるかには、一般に満足しています。

私はデータセット全体をループし、毎月のPDFプロットを作成したいと思います。これを行う上での助けに感謝します!

import glob, os 
import pandas as pd 
from pandas import Series, DataFrame, Panel 
import numpy as np 
import matplotlib.pyplot as plt 

wind = pd.read_csv('2014.csv') 

wind['Date']=pd.to_datetime(wind['Date']) 
wind=wind.set_index('Date') 

dates = pd.date_range('2014-01', '2014-2', freq='1min') 

janwin = Series(wind['Speed'], index=dates) 
jandir = Series(wind['Dir'], index=dates) 

plt.figure(1) 
plt.subplot(211) 
plt.plot(dates, janwin) 

plt.ylabel("Km/hr") 
plt.rcParams.update({'font.size': 4}) 
plt.grid(which='major', alpha = .5) 


plt.subplot(212) 
plt.plot(dates, jandir) 
plt.ylabel("Degrees") 
plt.rcParams.update({'font.size': 4}) 
plt.grid(which='major', alpha = 5) 
plt.ylim(0,360) 
plt.axis(minor=True) 

plt.savefig('test.pdf', dpi=900) 
にStackOverflowに

Sample Plot

答えて

1

ようこそ。通常、この種の問題について支援を求めているときは、特定のインスタンスや問題を抱えてから助けを求めるまで仕事をするのが最善です。このような広範なことをする方法を伝えることは非常に難しく、怠け者で問題を解決するのではなく、助けを求めているように、しばしば良い反応を得ることはありません。取り組む必要のあるいくつかの問題がありますが、ループを設定してループを開始/停止する方法と、現在興味がある月のデータをプロットするしか方法がわかりません。

以下は、私がメモリからすばやく書いたサンプルコードです(実行されていません)。これを行うにはより良い方法があると確信していますが、うまくいけば正しい軌道に乗ります。将来的には、あなたの投稿を基本部分に引き出すことができれば、最高の反応を得るでしょう。この場合、毎日2か月のサンプルデータフレームが反復/プロットを取得するのに役立つでしょう。その後、作業コードを取り出して分に調整することができます。

ここをクリックして、ここに記載されている最終的なコードがあなたに続く人に役立つことを確認してください。

import pandas as pd 
import matplotlib.pyplot as plt 
import datetime 
from dateutil.relativedelta import relativedelta 
import calendar 

#wind = pd.read_csv('2014.csv') 
data = [['2014-01-01 00:00:00', 13, 179], 
     ['2014-01-01 00:01:00', 13, 178],['2014-01-01 00:02:00', 11, 169],['2014-01-01 00:03:00', 11, 178], 
     ['2014-01-01 00:04:00', 11, 181]] 

rawDf = pd.DataFrame(data, columns = ['Date','Speed','Dir']) 

rawDf['Date']=pd.to_datetime(rawDf['Date']) 

#Define beginning and end of loop - start at first month, end at last month 
currDate = datetime.date(rawDf['Date'].min().year, rawDf['Date'].min().month, 1) 
endDate = datetime.date(rawDf['Date'].max().year, rawDf['Date'].max().month, 1) 


#loop 
while currDate <= endDate: 

    currMoEnd = datetime.date(currDate.year, currDate.month, calendar.monthrange(currDate.year,currDate.month)[1]) 
    wind = rawDf[(rawDf['Date']>= currDate) & (rawDf['Date']<= currMoEnd)] 
    wind.set_index('Date', inplace = True) 

    dates = pd.date_range(currDate, currMoEnd, freq='1min') 

    janwin = pd.Series(wind['Speed'], index=dates) 
    jandir = pd.Series(wind['Dir'], index=dates) 

    plt.figure(1) 
    plt.subplot(211) 
    plt.plot(dates, janwin) 

    plt.ylabel("Km/hr") 
    plt.rcParams.update({'font.size': 4}) 
    plt.grid(which='major', alpha = .5) 


    plt.subplot(212) 
    plt.plot(dates, jandir) 
    plt.ylabel("Degrees") 
    plt.rcParams.update({'font.size': 4}) 
    plt.grid(which='major', alpha = 5) 
    plt.ylim(0,360) 
    plt.axis(minor=True) 

    plt.show() 
    plt.savefig('{0}_output.pdf'.format(datetime.stftime(currDate,'%Y-%m')), dpi=900) 

    currDate = currDate + relativedelta(months = 1) 
+0

私は月間にどのようにループするのか分からず、どうやったらいいか分かりませんでした。これは大きな助けになる、私は他の人が従うという例があると、私はその投稿を更新するだろう。ありがとう! –

1

データをループする方法を示すためのflyingmeatballに感謝します。私は最初のスクリプトを通して多くのことを学びました。うまくいけば、他の誰かの参考になるでしょう。

以下のコードは、日付/時間フィールドで1分の平均風向データを含むcsvを読み込み、毎月の速度と方向の両方の時系列を含む図をプロットします。

編集:これを投稿して以来、私は、月の最終日の最初のタイムスタンプ(データの24時間分が欠落しています)にデータをプロットしていることに気付きました。これは、CurrMoEndが日付のみを返すためです。

#Plots monthly wind speed data from 1min average recordings to PDF 
import pandas as pd 
import matplotlib.pyplot as plt 
import datetime 
from dateutil.relativedelta import relativedelta 
import calendar 


data = pd.read_csv('data.csv') 

data['Date']=pd.to_datetime(data['Date']) 

rawDf = pd.DataFrame(data, columns = ['Date','Speed','Dir']) 


#Define beginning and end of loop - start at first month, end at last month 
currDate = datetime.date(rawDf['Date'].min().year, rawDf['Date'].min().month, 1) 
endDate = datetime.date(rawDf['Date'].max().year, rawDf['Date'].max().month, 1) 


#loop through and plot each month of data 
while currDate <= endDate: 

currMoEnd = datetime.date(currDate.year, currDate.month, calendar.monthrange(currDate.year,currDate.month)[1]) 
wind = rawDf[(rawDf['Date']>= currDate) & (rawDf['Date']<= currMoEnd)] 
wind.set_index('Date', inplace = True) 

dates = pd.date_range(currDate, currMoEnd, freq='1min') 

win = pd.Series(wind['Speed'], index=dates) 
dirc = pd.Series(wind['Dir'], index=dates) 

#Set figure size roughly to A4 paper size 
plt.figure(1, figsize = (11.3, 8)) 

plt.subplot(211) 
plt.plot(dates, win, lw = 0.15) 
plt.ylabel("Km/hr") 
plt.rcParams.update({'font.size': 4}) 
plt.grid(which='major') 


plt.subplot(212) 
plt.plot(dates, dirc, lw = 0.15) 
plt.ylabel("Degrees") 
plt.rcParams.update({'font.size': 4}) 
plt.grid(which='major') 
plt.yticks([0, 45, 90, 135, 180, 225, 270, 315, 360]) 
plt.ylim(0,360) 
plt.axis(minor=True) 

#convert current month to for file name 
month = int(currDate.strftime('%m')) 
year= int(currDate.strftime('%Y')) 

#Plot PDF to current directory/year/month output.pdf 
plt.savefig("{}/{} Output.pdf".format(year, month), dpi = 900) 
plt.show() 

#increment current date  
currDate = currDate + relativedelta(months = 1) 
関連する問題