Warning: Undefined variable $position in /home/pystyles/pystyle.info/public_html/wp/wp-content/themes/lionblog/functions.php on line 4897

matplotlib – stackplot で積み上げ折れ線グラフを作成する方法

matplotlib – stackplot で積み上げ折れ線グラフを作成する方法

概要

matplotlib の pyplot.stackplot() で積み上げ折れ線グラフを作成する方法について紹介します。

Advertisement

pyplot.stackplot

matplotlib.pyplot.stackplot(x, *args, labels=(), colors=None, baseline='zero', data=None, **kwargs)

引数

名前 型 デフォルト値 x 形状が (N,) の1次元配列 x の値

y 形状が (M, N) の2次元配列、または形状が (N,) の1次元配列 y の値は累積した値でないことを仮定しています。 baseline {‘zero’, ‘sym’, ‘wiggle’, ‘weighted_wiggle’} ‘zero’ ベースラインの計算方法 labels 要素数が N のラベル一覧 () 各データに割り当てるラベル colors 要素数が N の色一覧 None 各データに割り当てる色

**kwargs Axes.fill_between() に渡せる引数 </tbody> </table> </div> </div> ​

stackplot(x, y1, y2, y3) または stackplot(x, [y1, y2, y3]) で指定します。 また、y1, y2, y3 に対応するラベルは labels 引数で指定できます。

In [1]:
import numpy as np
from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [1, 1, 2, 3, 5]
y2 = [0, 4, 2, 6, 8]
y3 = [1, 3, 5, 7, 9]
labels = ["Fibonacci ", "Evens", "Odds"]

fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3, labels=labels)
ax.legend(loc="upper left")

fig, ax = plt.subplots()
ax.stackplot(x, [y1, y2, y3], labels=labels)
ax.legend(loc="upper left")

plt.show()

積み上げる際の起点を設定する

baseline 引数でどこを起点に積み上げるかを指定できます。

In [2]:
import numpy as np
from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [1, 1, 2, 3, 5]
y2 = [0, 4, 2, 6, 8]
y3 = [1, 3, 5, 7, 9]

fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3, baseline="sym")

plt.show()

色を設定する

y1, y2, y3 に対応するラベルは colors 引数で指定できます。

In [3]:
import numpy as np
from matplotlib import pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [1, 1, 2, 3, 5]
y2 = [0, 4, 2, 6, 8]
y3 = [1, 3, 5, 7, 9]

fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3, colors=["r", "b", "g"])

plt.show()