時系列データ分析の可視化
僕が普段扱っているデータ(エネルギーデータ)の可視化をPythonを使って行うためのメモです。
Githubにまとめもあげています。
エネルギーデータの分析にPythonを使うときの参考になればと思っています。私も勉強中なのでこんなのがあればというものがあれば教えてください。m(_ _;)m
※あくまで、普段使っているエネルギーデータに対応したものなので、適宜変更していただければと思います。また、使用データはGithubに置いています。
概要
- エネルギーデータを使用(1h間隔のデータ)
- 使用言語はPython
- 可視化は、pandasのplot, matplotlib, seabornなど
- githubではJupyterNotebookで実現
- Pandas,Seabornの両方で行っているものもあります
- Bokehも使ってインタラクティブなチャートも使いたい
#使用データ
データ読み込み
# データ確認
"""
データに関して
Github上にあるデータは、1時間毎に区切られた積算及び計測データです。
2017年度のデータを使用しています。
"""
#vis_dfにcsvファイルを読み込みます。
"""
index_col:csvファイルの何列目にindexがあるか指定
engine:pythonを指定することで日本語ヘッダを文字化けせずに読み込める
parse_dates:datetime型で読み込む列を指定([]をつけて、列番号で指定)
header:ヘッダが何行目にあるか
skiprows:読み込む際に読み飛ばす行を指定([]をつけて、特定の行のみ除外するように指定)
"""
vis_df = pd.read_csv(r'use_data/energy_data.csv',
index_col=0,
engine='python',
parse_dates=[0],
header=0,
skiprows=[1]
)
電力量データ
月別データ
Pandas
- ['受電 電力量']:可視化したい列の名称(ヘッダ)
- kind='bar':棒グラフで表現
- colormap='Wistia':色の選択(電力量なので黄色)
pandas(月別データ)
# 可視化(pandasを利用した場合)
vis_df_month['受電 電力量'].plot(kind='bar',colormap='Wistia')

Seaborn
- x=vis_df_month.index:pandasデータフレームのindex(x軸)
- y = vis_df_month['受電 電力量']:可視化したい列の名称
- color='yellow':色の選択(電力量なので黄色)
seaborn(月別データ)
# 可視化(seabornを利用した場合)
sns.barplot(x=vis_df_month.index,y = vis_df_month['受電 電力量'],color='yellow')
- Bar

月別用途別データ
Pandas
- Bar
pandas(月別用途別データ)
# 可視化(pandasを利用した場合)
'''
vis_df_month.columns.str.startswith('電力量用途')の文言は、
ヘッダ行を検索して、先頭文字列にシングルクォートで囲まれた文字列が含まれているものを
選択する処理を行っている。
'''
vis_df_month.loc[:,vis_df_month.columns.str.startswith('電力量用途')].plot(kind='bar',colormap='Wistia')
# 積み重ねる場合
'''
stacked: Trueにすると積み重ねることができる。
'''
vis_df_month.loc[:,vis_df_month.columns.str.startswith('電力量用途')].plot(stacked=True,kind='bar',colormap='Wistia')

- Pie
pandas(月別用途別データ)
# 可視化(pandasを利用した場合)
'''
Pieチャートで月毎の利用用途の可視化
4行書いたのは見栄えのため。良い方法ある?
loc[]:可視化に必要な範囲(日付指定)
columns.str.startswith('電力量用途'):「電力量用途」を先頭一致でヘッダから検索し、一致したものを可視化
'''
vis_df_month.loc['2017/04':'2017/06',vis_df_month.columns.str.startswith('電力量用途')].T.plot(kind='pie',figsize=(21,7),subplots=True,colormap='autumn')
vis_df_month.loc['2017/07':'2017/09',vis_df_month.columns.str.startswith('電力量用途')].T.plot(kind='pie',figsize=(21,7),subplots=True,colormap='autumn')
vis_df_month.loc['2017/10':'2017/12',vis_df_month.columns.str.startswith('電力量用途')].T.plot(kind='pie',figsize=(21,7),subplots=True,colormap='autumn')
vis_df_month.loc['2018/01':'2018/03',vis_df_month.columns.str.startswith('電力量用途')].T.plot(kind='pie',figsize=(21,7),subplots=True,colormap='autumn')

相関データ
Seaborn
seaborn(相関データ)
# 外気温度に対する電力量の相関,受電電力量に対する各用途の相関の確認
"""
x_vars=['外気温','受電 電力量']:x軸にする列を指定
y_vars=vis_df_month.columns[vis_df_month.columns.str.startswith('ガス量')]:y軸にする列を指定
"""
sns.pairplot(vis_df_month['2017/10':'2018/03'],
x_vars=['外気温','受電 電力量'],
y_vars=vis_df_month.columns[vis_df_month.columns.str.startswith('電力量')],
kind = 'reg',
size = 4,
)

- 特定の組み合わせだけの相関を見たい場合はこれで十分かと思います。
Seaborn.jointplot(相関データ)
# 特定の相関関係を見るときに使用
# 同時にヒストグラムも表示
# 夏期
sns.jointplot(x = '外気温',# x軸の値を文字列で指定(データフレーム内のカラム名)
y = '受電 電力量',# y軸の値を文字列で指定(データフレーム内のカラム名)
# [(vis_df.index.hour >= 8) & (vis_df.index.hour <= 18)] : 8時から18時までのデータを使用
# ['20170701':'20170930']:期間は、20170701から20170930までを使用
data=vis_df[(vis_df.index.hour >= 8) & (vis_df.index.hour <= 18)]['20170701':'20170930'],
kind='scatter',# グラフ種類を文字列で指定
color='orange', # plotの色を指定
edgecolor='black', # plotの枠線の色を指定
xlim=(0,40),# x軸の上下限値をタプルで入力
ylim=(0,400),# y軸の上下限値をタプルで入力
)

- 普段は夏と冬しかあまり使いませんが、色分けするとなんとなく傾向を把握することができます。
- 事前に'Season'列を作成して、グループ分けできるようにしたうえで、hueによってグループごとに色分けしています。
seaborn.relplot(相関データ)
# Dataframeに夏と冬の属性を加える
#vis_dfにSeason列を追加して、それぞれ季節ごとのグラフにする。
"""
[(vis_df.index.month >= 3 ) & (vis_df.index.month <= 5 ),'Season'] ='spring': 3月から5月まではspringにする。
[(vis_df.index.month >= 12 ) | (vis_df.index.month <= 2 ),'Season'] ='winter':年をまたぐので12月以上もしくは2月未満の月は冬と指定
"""
vis_df['Season'] = pd.Series()
vis_df.loc[(vis_df.index.month >= 3 ) & (vis_df.index.month <= 5 ),'Season'] ='spring'
vis_df.loc[(vis_df.index.month >= 6 ) & (vis_df.index.month <= 9 ),'Season'] ='summer'
vis_df.loc[(vis_df.index.month >= 10 ) & (vis_df.index.month <= 11 ),'Season'] ='autumn'
vis_df.loc[(vis_df.index.month >= 12 ) | (vis_df.index.month <= 2 ),'Season'] ='winter'
sns.relplot(x = '外気温',# x軸の値を文字列で指定(データフレーム内のカラム名)
y = '受電 電力量',# y軸の値を文字列で指定(データフレーム内のカラム名)
# [(vis_df.index.hour >= 8) & (vis_df.index.hour <= 18)] : 8時から18時までのデータを使用
data=vis_df[(vis_df.index.hour >= 8) & (vis_df.index.hour <= 18)],
kind='scatter',# グラフ種類を文字列で指定
palette='Set1', # plot群の色を指定
edgecolor='black', # plotの枠線の色を指定
hue='Season', #Season列のデータごとにplotを色分け
)
相関(sns.FacetGrid)
%config InlineBackend.figure_format ='retina' #きれいな画像にするおまじない
sns.set(font_scale=1.4) #文字サイズの決定
plt.rcParams['font.family'] = 'IPAPGothic' #日本語入力を可能にする
vis_df['hour'] = vis_df.index.hour #hour列を追加する
# 夏データ
grid = sns.FacetGrid(vis_df[(vis_df.index.month >= 7 ) & (vis_df.index.month <= 9 )],
sharex=True,
col='hour', # グラフを何の列でわけるか
hue='hour', #hour毎に色を分ける
palette='Oranges',
col_wrap=6 # 何列でグラフをずらすか
)
grid.map(plt.scatter,'外気温',r'受電 電力量',edgecolors='black')
#まとめ
こんな形で随時作っていこうと思います。Qiitaの編集およびGithubの更新を行っていきます。
時系列データの分析に有用なやり方があれば教えていただけると幸いです。