【matplotlib】横棒グラフ:barh, broken_barh

基本

棒グラフはbarhを使ってプロットします。
基本的な棒グラフを生成するサンプルコードをまず示します。

>>> import matplotlib.pyplot as plt

>>> y = [1, 2, 3, 4]
>>> width = [10, 20, 30, 10]

>>> fig, ax = plt.subplots()

>>> ax.barh(y=y, width=width)

応用

左の開始位置を変える:left

左の開始位置をleft引数で変更できます。

開始位置を5に変更してみます。

>>> ax.barh(y=y, width=width, left=5)

y軸のメモリの位置の調整:align

y軸のメモリの位置はalign引数で変更できます。
デフォルトはalign=’center’となっています。
align=’edge’とし、メモリの位置を変更してみます。

>>> ax.barh(y=y, width=width, align='edge')

 

おまけ:broken_barhについてのメモ

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

start_period = 0

bar1 = [(0, 7), (10, 5), (25, 4)]   # (スタート地点、長さ)
bar2 = [(0, 1), (22, 3), (40, 2)]   # (スタート地点、長さ)

yrange1 = [2, 1]     # bar1の軸についての設定(y値、幅)
yrange2 = [-2, .2]   # bar2の軸についての設定(y値、幅)

ax.broken_barh(xranges=bar1, yrange=yrange1, facecolor='red')
ax.broken_barh(xranges=bar2, yrange=yrange2, facecolor='green')
plt.savefig("result.png")
plt.show()

# 参考文献
# https://stackoverflow.com/questions/24425908/matplotlib-how-to-use-timestamps-with-broken-barh

参考文献

https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.barh.html#examples-using-matplotlib-pyplot-barh

タイトルとURLをコピーしました