【Numpy&Matplotlib】 Python 軸を日付フォーマットに変更
こんにちは今日はx軸を日にちのフォーマットに変更する方法です。
DataFlame
まずは使用するデータフレームをファイルから読み込んでください。
今回私は適当に作成したデータを使います。
print(df)
Year | Month | Day | Hour | Minute | Data | |
---|---|---|---|---|---|---|
0 | 2019 | 1 | 1 | 0 | 1 | 1.683375 |
1 | 2019 | 1 | 1 | 0 | 6 | 1.732797 |
2 | 2019 | 1 | 1 | 0 | 11 | 0.985744 |
3 | 2019 | 1 | 1 | 0 | 16 | 1.522657 |
4 | 2019 | 1 | 1 | 0 | 21 | 0.726131 |
... | ... | ... | ... | ... | ... | ... |
105115 | 2019 | 12 | 31 | 23 | 36 | 1.442926 |
105116 | 2019 | 12 | 31 | 23 | 41 | 1.532434 |
105117 | 2019 | 12 | 31 | 23 | 46 | 1.513058 |
105118 | 2019 | 12 | 31 | 23 | 51 | 0.594683 |
105119 | 2019 | 12 | 31 | 23 | 56 | 0.767968 |
105120 rows × 6 columns
1日当たりのDataの平均値を時系列プロットしてみます
#日平均
import calendar
xdata = []
year=2019
for j in range(12):
month=j+1
x=calendar.monthrange(year, month)[1] #*1
df2 = df.loc[df["Month"]==month]
for i in range(x):
day = i + 1
xdata0 = df2.loc[df2["Day"]==day]["Data"].mean()
xdata.append(xdata0)
Keys
1) year年month月の日数を取ることができる。
例えばyear=2019 month=1 の時、x=31となる。
それではグラフを書いてみます。横軸はDN(Day Number)です。
import matplotlib.pyplot as plt
#グラフ作成
fig = plt.figure(figsize=(20,5))
plt.rcParams["font.size"] = 16
ax = plt.subplot(111)
ax.plot(np.arange(1,366), xdata)
ax.set_xlabel("DN")
ax.set_ylabel("Data")
ax.set_xlim(0,365)
plt.show()
fig.savefig("XXX.png",format="png", dpi=330)
DN⇒Datetime
次に横軸を日付にします。
time = []
year = 2019
for i in range(12):
month = i + 1
x=calendar.monthrange(year, month)[1]
for j in range(x):
day = j + 1
t = "{0:04d}-{1:02d}-{2:02d}".format(year, month, day) #1*
time.append(pd.to_datetime(t)) #*2
Keys
1) format文⇓
2)pd.to_datetime("2019-01-01 01:30:00:00")⇒Timestamp("2019-01-01 01:30:00:00")
オブジェクト⇒datetimeに変換されます
グラフ
#データの選択
x = time
y = xdata
#グラフ作成
fig = plt.figure(figsize=(20,5))
plt.rcParams["font.size"] = 16
ax = plt.subplot(111)
ax.plot(x, y)
#ラベル設定
ax.set_title(" ")
ax.set_ylabel("data")
ax.set_xlabel("Time")
#軸の設定 *1
ax.minorticks_on()
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")
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_xlim(datetime.datetime(2019, 1, 1), datetime.datetime(2019, 12, 31))
plt.show()
fig.savefig("XXX.png",format="png", dpi=330)
Keys
1)軸の設定
それでは 🌏