4
5

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.

pyplotでガントチャートを作ってみた

Posted at

Summary

  • matplotlib.pyplot.barhを使って横棒グラフを描画する
  • width引数で棒の幅、left引数で棒のオフセット位置を指定

hoge.png

Code

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

# 描画用データ、csvなどから取り込んでこの形にしても良い
periods = [
    ["one",   dt.datetime(2021,  4,  1), dt.datetime(2021,  8,  1)],
    ["two",   dt.datetime(2021,  6,  1), dt.datetime(2021,  8,  1)],
    ["three", dt.datetime(2021,  8,  1), dt.datetime(2021, 10,  1)],
]

# barhがy軸正方向に描画していくので、ガントチャートらしくなるよう逆向きにする
periods.reverse()
# periodsが2重のlistになっているので、行と列を入れ替えて取り出す
titles, begins, ends = list(zip(*periods))

# pyplot内でDatesとして扱われるように変換
edate, bdate = [mdates.date2num(item) for item in (ends, begins)]

# 実際に描画
fig, ax = plt.subplots()
ax.barh(y=titles, width=edate - bdate, left=bdate)
#  横軸目盛の表示形式をdateに変更する
ax.xaxis_date()

# 描画
plt.savefig("hoge.png")
# plt.show()

補足情報

  • ガントチャートのy軸はラベルが長くなりやすいので
    • plt.subplots(figsize=(12, 6)) などでグラフを横長にする
    • fig.subplots_adjust(left=0.5, right=0.95) などでyticksラベル用の領域を増やせる
  • y軸の順序が意図したとおりにならない場合
    • ax.barh(y=range(len(titles), ...) ax.yticks(range(len(titles)), titles) としてtitlesの順序通りにできる
  • ax.xaxis.set_major_formatter() でx軸の表示形式をいじれる
  • ax.xaxis.set_major_locator() で主目盛、minor にすれば補助目盛の間隔をいじれる
    • より詳細にいじるには bdate などと同じ用に xticks を作成して ax.set_xticks(xticks, minor=False) などで指定可能
    • 最大・最小は ax.set_xlim(bdate[-1], edate[0]) などして揃えられる
4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?