matplotlib - 折れ線グラフを作成する。
概要
matplotlib で折れ線グラフを作成する方法について紹介する。
基本的な使い方
折れ線グラフは pyplot.plot または axes.Axes.plot で作成できる。
import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, np.pi * 2, 100) y = np.sin(x) # 折れ線グラフを作成する。 fig, axes = plt.subplots(figsize=(4, 4)) axes.plot(x, y) plt.show()
1つの Axes に2つの折れ線グラフを作成する。
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, np.pi * 2, 100) y1 = np.sin(x) y2 = np.cos(x) fig, axes = plt.subplots(figsize=(4, 4)) axes.plot(x, y1) axes.plot(x, y2) plt.show()
階段状の折れ線グラフを作成する。
階段状の折れ線グラフを作成するためのヘルパー関数である。
- axes.Axes.step: 階段状の折れ線グラフを作成する。
- pyplot.step: 階段状の折れ線グラフを作成する。
import numpy as np import matplotlib.pyplot as plt x = np.arange(10) y1 = np.sin(x * 0.5) y2 = y1 - 0.5 y3 = y1 - 1 fig, ax = plt.subplots() ax.step(x, y1, where='pre', label='pre') ax.step(x, y2, where='mid', label='mid') ax.step(x, y3, where='post', label='post') ax.legend() ax.set_xticks(x) ax.grid() plt.show()