2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

matplotlib でX軸にラベルに時間(分)を使うときのサンプル

Last updated at Posted at 2020-12-16

#テストデータ

import pandas as pd 

tm=pd.date_range("2020/2/3 9:00" ,"2020/2/3 11:00" , freq="60min")

dt1=range(len(tm))
dt2=range(0,-len(tm),-1)

df=pd.DataFrame({"tm":tm , "dt1":dt1 , "dt2":dt2})

print(df.to_markdown()) 

tm dt1 dt2
0 2020-02-03 09:00:00 0 0
1 2020-02-03 10:00:00 1 -1
2 2020-02-03 11:00:00 2 -2

#X軸を共有にして2つのグラフを書く。その時、横軸は1分おきに軸線を書き、5分おきにラベルを書く

import matplotlib.pyplot as plt
import matplotlib.dates as mdates

#sharex="col"でX軸を共通にする
fig ,ax = plt.subplots(2 , 1, sharex="col", figsize=(10 , 20))

ax[0].plot("tm" , "dt1" ,data=df)
ax[0].grid(True)

ax[1].plot("tm" , "dt2" ,data=df)
ax[1].grid(True)


#x軸の描画の範囲を指定。これを入れないと、時刻がうまくそろわない
ax[1].set_xlim(tm[0] , tm[-1])   


#5分おきにラベル
Minute1=mdates.MinuteLocator(range(60),5)   
ax[1].xaxis.set_major_locator(Minute1)

#1分おきに軸線
Minute2=mdates.MinuteLocator(range(60),1)   
ax[1].xaxis.set_minor_locator(Minute2)

#H:M のフォーマットでラベルを書く
Minute_fmt = mdates.DateFormatter('%H:%M')  
ax[1].xaxis.set_major_formatter(Minute_fmt)


#縦書きの指定
plt.setp(ax[1].get_xticklabels(), rotation=90, ha="right")

#表示
plt.show()

#結果
image.png

#参考
matplotlibでx軸の時刻情報をフォーマットする
dates.MinuteLocator

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?