Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Matplotlibの折れ線グラフ

公開日 2023-08-10

Matplotlibで折れ線グラフをプロットするには、ax.plotを使用します。ax.plotの簡単な例を以下に示します。

import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 3, 4]) # 横軸の値
y = np.array([5, 3, 7, 4]) # 縦軸の値

fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()
<Figure size 640x480 with 1 Axes>

上に示すように、ax.plotの最初の引数は横軸の値、2番目の引数は縦軸の値とします。

複数系列の折れ線グラフ

折れ線を追加したい場合、以下のように配列のサイズを(横軸の点数)×(折れ線の数)とします。

y2 = np.array([[5, 3],
               [3, 6],
               [7, 2],
               [4, 1]])

fig, ax = plt.subplots()
ax.plot(x, y2)
plt.show()
<Figure size 640x480 with 1 Axes>

または、以下のようにax.plotを追加することでも線を追加できます。

y3 = np.array([3, 6, 2, 1])

fig, ax = plt.subplots()
ax.plot(x, y)
ax.plot(x, y3)
plt.show()
<Figure size 640x480 with 1 Axes>

線の太さ・色・種類を変える

線の太さを変える場合、linewidthオプションで指定します。値が大きいほど、線が太くなります。 また、線の種類と色は、それぞれlinestyle, colorオプションで指定します。

fig, ax = plt.subplots()
ax.plot(x, y, linewidth=5, color="black")
plt.show()
<Figure size 640x480 with 1 Axes>
fig, ax = plt.subplots()
ax.plot(x, y, linestyle="solid") # 実線(デフォルト)
ax.plot(x, 0.8*y, linestyle="dashed") # 破線
ax.plot(x, 0.6*y, linestyle="dashdot") # 一点鎖線
ax.plot(x, 0.4*y, linestyle="dotted") # 点線
plt.show()
<Figure size 640x480 with 1 Axes>

linewidth, linestyleオプションの詳細は以下の記事を参考にして下さい。

Matplotlib 線の書式

また、colorオプションの詳細は以下の記事を参考にして下さい。

Matplotlib 色の書式

マーカーを表示する

データのマーカーを表示するには、markerオプションを使用します。

fig, ax = plt.subplots()
ax.plot(x, y, marker="o")
ax.plot(x, 0.8*y, marker="v")
ax.plot(x, 0.6*y, marker="s")
ax.plot(x, 0.4*y, marker="+")
ax.plot(x, 0.2*y, marker="o")
ax.plot(x, 0*y, marker="D")
plt.show()
<Figure size 640x480 with 1 Axes>

主なmarkerオプションを以下の表に示します。

marker説明
o
v下向き三角
^上向き三角
<左向き三角
>右向き三角
s四角形(square)
p五角形(pentagon)
++記号
xx記号
Dダイヤモンド

その他に利用可能なマーカーの種類は、以下の公式ページを参照してください。

matplotlib.markers — Matplotlib documentation

マーカーの枠線の太さ・色などは変更できます。指定できるオプションを以下の表に示します。

オプション説明
markersizeマーカーの大きさ
markeredgewidthマーカー枠線の太さ
markeredgecolorマーカー枠線の色
markerfacecolorマーカーの塗潰しの色
fillstyleマーカーの塗潰しスタイル。full (デフォルト), left, right, bottom, top, none (塗潰し無し)
markerfacecoloraltマーカーの塗潰しの色2。fillstyleでleft, right, bottom, topを指定した際、塗り潰されない領域の色となる

これらのオプションを使用した例を以下に示します。マーカーの枠線が赤、左半分が緑、右半分が青となります。

fig, ax = plt.subplots()
ax.plot(x, y, marker="o", markersize=20, markeredgecolor="red", markeredgewidth=2, 
        markerfacecolor="green", fillstyle="left", markerfacecoloralt="blue")
plt.show()
<Figure size 640x480 with 1 Axes>