【Matplotlib】Python Matplotlib時系列プロット(気温ー日平均)
こんにちは! 今日は時系列プロットを紹介します。
時系列プロット
データの取得
縦軸は気温データで、横軸は時間です。
データは気象庁の気温データ(時間平均値)を使用しました。
気象庁|過去の気象データ・ダウンロード
データフレーム(df)の扱い
私のanacondaは日本語を表示する設定をしていないので、
まずはダウンロードしたデータの日本語を英語に変換しました。
(時間→Time, 気温→Temperature ,.... )
それでは必要なモジュールをいれて、データをdfに入れていきます。
import numpy as np
df = pd.read_csv("data/tokyo_temp_2019.csv", header=4) df.head()
Time | Temperature | Info | num | |
---|---|---|---|---|
0 | 2019/1/1 1:00 | 1.4 | 8 | 1 |
1 | 2019/1/1 2:00 | 2.1 | 8 | 1 |
2 | 2019/1/1 3:00 | 1.5 | 8 | 1 |
3 | 2019/1/1 4:00 | 1.4 | 8 | 1 |
4 | 2019/1/1 5:00 | 1.1 | 8 | 1 |
ファイルタイプがcsvだったのでread_csvを使います。
(csv=Comma Separated Value カンマ区切りの値)という意味
headerは読み飛ばす行を設定します。
それぞれのデータを見てみます。
print(len(df)) print(df.dtypes)
⇒
8760
Time object
Temperature float64
Info int64
num int64
dtype: object
気温がobjectだったので、タイプを日付に変換し、dfの右に貼り付けます。
名前はTime(dt)とします
df["Time(dt)"] = pd.to_datetime(df["Time"]) df
Time | Temperature | Info | num | Time(dt) | |
---|---|---|---|---|---|
0 | 2019/1/1 1:00 | 1.4 | 8 | 1 | 2019-01-01 01:00:00 |
1 | 2019/1/1 2:00 | 2.1 | 8 | 1 | 2019-01-01 02:00:00 |
2 | 2019/1/1 3:00 | 1.5 | 8 | 1 | 2019-01-01 03:00:00 |
3 | 2019/1/1 4:00 | 1.4 | 8 | 1 | 2019-01-01 04:00:00 |
4 | 2019/1/1 5:00 | 1.1 | 8 | 1 | 2019-01-01 05:00:00 |
これで準備は完成です!
グラフ描画
まずは、描写に必要なモジュールをインポートします。
import numpy as np import matplotlib.pyplot as plt from matplotlib import dates as mdates *1 from matplotlib.dates import DateFormatter *1 import datetime *1
1.日付の設定に必要なモジュール
描写していきます!
#データの選択 x = df["Time(dt)"] y = df["Temperature"] #グラフ作成 fig = plt.figure(figsize=(20,5)) #fontsizeを一括管理 plt.rcParams["font.size"] = 16 ax = plt.subplot(111) #データのプロット ax.plot(x, y, linewidth=1) #ラベル設定 ax.set_title("Temperature 2019 Tokyo") ax.set_ylabel("Temperature ($\mathrm{^\circ C}$)") ax.set_xlabel("Time") #軸の設定 ax.minorticks_on() #補助目盛も設定に必要*2 #*3 ax.tick_params(axis="both", which="major",direction="in",length=7,width=2,top="on",right="on") ax.tick_params(axis="both", which="minor",direction="in",length=4,width=1,top="on",right="on") #*4-1,2,3 ax.xaxis.set_major_formatter(DateFormatter("%b-%d")) ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2)) ax.xaxis.set_minor_locator(mdates.MonthLocator(interval=1)) #範囲設定 ax.set_ylim(y.min()*1.2, y.max()*1.2) #気温の最小値、最大値の1.2倍を範囲とした ax.set_xlim(datetime.datetime(2019, 1, 1), datetime.datetime(2019, 12, 31)) #*5 plt.show() fig.savefig("XXX.png",format="png", dpi=330)
2) x軸の後に入れると、時間軸に変な補助線が入るので、必ず前に!
3) axis: "both", "y", "x"を入れる
which: majorは主目盛、minorは補助目盛
direction: メモリの方向"in", "out"
length: メモリの長さ
width: メモリの太さ
top, right, left, bottom: どの方向を利用するか
4-1) 主目盛のフォーマット
%b-%dで、月(英語表示)-日
4-2) 主目盛の間隔
MonthLocaterで月間隔
intervalで間隔を設定
4-3) 補助目盛の間隔
MonthLocaterで月間隔
intervalで間隔を設定
5) datetime.datetimeで範囲設定
参考
時間軸の設定
Date tick labels — Matplotlib 3.3.3 documentation
matplotlib.dates — Matplotlib 3.3.3 documentation
それでは 🌏