〰️

# matplotlibで枠線を書く:点線の縁取り

2023/03/30に公開

## はじめに

`matplotlib`で作成した線を枠線で縁取ったことはありますか？

## 結論

`matplotlib.patheffects`で枠線の設定をしよう！！

``````import matplotlib.pyplot as plt
import matplotlib.patheffects as pe

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

lw = 5

line_style = dict(linestyle='--',linewidth=lw, color='r' , path_effects=[pe.Stroke(linewidth=lw+2, foreground='b'), pe.Normal()])
plt.plot(x, y, **line_style)
``````

## 枠線の作り方

### 良くない例

この方法は以下のように書け、実線の場合にうまくいきます。

``````import matplotlib.pyplot as plt
import matplotlib.patheffects as pe

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

lw = 5

line_style = dict(linewidth=lw+2, color='b')
plt.plot(x, y, **line_style)

line_style = dict(linewidth=lw, color='r')
plt.plot(x, y, **line_style)
``````

``````import matplotlib.pyplot as plt
import matplotlib.patheffects as pe

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

lw = 5

line_style = dict(linestyle='--',linewidth=lw+2, color='b')
plt.plot(x, y, **line_style)

line_style = dict(linestyle='--',linewidth=lw, color='r')
plt.plot(x, y, **line_style)
``````

### 良い例

``````import matplotlib.pyplot as plt
import matplotlib.patheffects as pe

x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

lw = 5

line_style = dict(linestyle='--',linewidth=lw, color='r' , path_effects=[pe.Stroke(linewidth=lw+2, foreground='b'), pe.Normal()])
plt.plot(x, y, **line_style)
``````