Matplotlibの折れ線グラフ#

公開日

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()
../_images/92af183b8baefd411bdf89aed5ea31c093b74864453daf68f65593158b304ad5.png

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

複数系列の折れ線グラフ#

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

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

fig, ax = plt.subplots()
ax.plot(x, y2)
plt.show()
../_images/6080e9fd711029a1173a8d37b060af444b82ebcf4277209226056458018c25ae.png

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

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

fig, ax = plt.subplots()
ax.plot(x, y)
ax.plot(x, y3)
plt.show()
../_images/6080e9fd711029a1173a8d37b060af444b82ebcf4277209226056458018c25ae.png

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

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

fig, ax = plt.subplots()
ax.plot(x, y, linewidth=5, color="black")
plt.show()
../_images/7062d95a58fa8442ef1c648e6a8fe6e3e92bfa14d628415fad0641746695d91b.png
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()
../_images/447210101d34a554003207113fdf22aaf7d18bbba5a99227252c07140fc16b0e.png

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()
../_images/26888393808026a879029afed8abd1ffeafc6f7195fe7f054942a998ccee12c3.png

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

marker

説明

o

v

下向き三角

^

上向き三角

<

左向き三角

>

右向き三角

s

四角形(square)

p

五角形(pentagon)

+

+記号

x

x記号

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()
../_images/8554d8e4d053fc9fc64c7955cb0832340d240f7499a6b6155fbeabb7d961638e.png