Matplotlib 線の書式#
※記事内に商品プロモーションを含むことがあります。
公開日
この記事では、Matplotlibの線の書式を設定する方法を解説します。
線の主な書式を以下の表に示します。
引数 |
説明 |
---|---|
linewidth/lw |
線の太さ |
color/c |
線の色 |
alpha |
色の透明度 |
linestyle |
線の種類 |
線の太さ#
線の太さはlinewidth
またはlw
で指定します。値が大きいほど線は太くなります。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 3, 2], linewidth=3, label="linewidth=3")
ax.plot([0, 2, 1], linewidth=10, label="linewidth=10")
ax.legend()
plt.show()

線の色#
線の色はcolor
またはc
で指定します。指定する方法は、red
やblue
などの文字列を与える他に、RGBや16進数のカラーコードで与えることなども可能です。
fig, ax = plt.subplots()
ax.plot([1, 3, 2], color="red", label="red")
ax.plot([0, 2, 1], color="blue", label="blue")
ax.legend()
plt.show()

線の透明度#
線の透明度はalpha
で指定します。alpha
は0から1の範囲を取り、値が小さいほど透明になります。デフォルトの値は1になります。
fig, ax = plt.subplots()
ax.plot([1, 3, 2], color="blue", alpha=1, label="alpha=1")
ax.plot([0, 2, 1], color="blue", alpha=0.6, label="alpha=0.6")
ax.plot([-1, 1, 0], color="blue", alpha=0.3, label="alpha=0.3")
ax.legend()
plt.show()

線の種類#
線の種類はlinestyle
またはls
で指定します。文字列または記号で指定できます。
文字列 |
記号 |
説明 |
---|---|---|
solid |
|
実線 |
dashed |
|
破線 |
dashdot |
|
1点鎖線 |
dotted |
|
点線 |
None |
|
線なし |
fig, ax = plt.subplots()
ax.plot([1, 3, 2], linestyle="solid", label="solid")
ax.plot([0, 2, 1], linestyle="dashed", label="dashed")
ax.plot([-1, 1, 0], linestyle="dashdot", label="dashdot")
ax.plot([-2, 0, -1], linestyle="dotted", label="dotted")
ax.plot([-3, -1, -2], linestyle="None", label="None")
ax.legend()
plt.show()

また、linestyle
には任意の線の種類を指定することもできます。以下のようにタプルを与えます。最初の要素でオフセットを指定し、以降でon
に線の長さ、off
に空白の長さを指定します。on
とoff
は繰り返し指定できます。
(offset, (on, off))
(offset, (on, off, on, off))
(offset, (on, off, on, off, on, off))
...
以下にオフセットの例を示します。青線はオフセット0
, オレンジの線はオフセット5
です。オレンジ線の一番左側は、通常の破線の半分の長さとなっています。
fig, ax = plt.subplots()
ax.plot([1, 3, 2], linestyle=(0, (10, 10)), label="(0, (10, 10))")
ax.plot([0, 2, 1], linestyle=(5, (10, 10)), label="(5, (10, 10))")
ax.legend()
plt.show()

また、以下に2点鎖線の例を示します。
fig, ax = plt.subplots()
ax.plot([1, 3, 2], linestyle=(0,(6,2,1,2,1,2)), label="(0,(6,2,1,2,1,2))")
ax.legend()
plt.show()
