2022/10/08:最終更新
はじめに
Pythonで四角形の枠線を複数個描画する方法を紹介します.
開発環境
Mac OS Montery v.12.6
Python 3.9.11
numpy = 1.23.3
matplotlib = 3.6.0
目次
- matplotlib.LineCollection()を使う方法
- matplotlib.patches.Rectangle()を使う方法
- matplotlib.pyplot.plot()を使う方法
matplotlib.LineCollection()を使う方法
rect_linecollection.py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
#変数の宣言
X_RECT=np.array([[[-2,-2],[-2,-1],[-1,-1],[-1,-2],[-2,-2]],
[[ 1 ,1],[ 1 ,2],[ 2, 2],[ 2 ,1],[ 1 ,1]],
[[ 1,-2],[ 1,-1],[ 2,-1],[ 2,-2],[ 1,-2]]])
#描画の宣言
fig=plt.figure()
gs=fig.add_gridspec(1,1)
ax1=fig.add_subplot(gs[0,0],aspect='equal')
#描画スタート
#LineCOllection
lc = LineCollection(X_RECT,color='b')
ax1.set_title('LineCollection')
ax1.set_xlim(-3,3)
ax1.set_ylim(-3,3)
ax1.add_collection(lc)
plt.show()
matplotlib.patches.Rectangle()を使う方法
rect_rectangle.py
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
#変数の宣言
X_CENTER=[(1.5,1.5),(1.5,-1.5),(-1.5,-1.5)]
#描画の宣言
fig=plt.figure(figsize=(19,6))
gs=fig.add_gridspec(1,1)
ax1=fig.add_subplot(gs[0,0],aspect='equal')
#描画スタート
#Rectangle
ax1.set_title('Rectangle')
ax1.set_xlim(-3,3)
ax1.set_ylim(-3,3)
for i in range(3):
r = patches.Rectangle( xy=X_CENTER[i] , fill=False,width=1, height=1,color='b') # 四角形のオブジェクト
ax1.add_patch(r)
plt.show()
matplotlib.pyplot.plot()を使う方法
rect_plot.py
import numpy as np
import matplotlib.pyplot as plt
#変数の宣言
X_RECT_PLOT=np.array([[[-2,-2,-1,-1,-2],[-2,-1,-1,-2,-2]],[[1,1,2,2,1],[1,2,2,1,1]],[[1,1,2,2,1],[-2,-1,-1,-2,-2]]])
X_RECT=np.array([[[-2,-2],[-2,-1],[-1,-1],[-1,-2],[-2,-2]],
[[ 1 ,1],[ 1 ,2],[ 2, 2],[ 2 ,1],[ 1 ,1]],
[[ 1,-2],[ 1,-1],[ 2,-1],[ 2,-2],[ 1,-2]]])
#描画の宣言
fig=plt.figure()
gs=fig.add_gridspec(1,1)
ax1=fig.add_subplot(gs[0,0],aspect='equal')
#描画スタート
#plot
X_RECT_PLOT=X_RECT.transpose(1,0,2)
ax1.set_xlim(-3,3)
ax1.set_ylim(-3,3)
ax1.set_title('plot')
ax1.plot(X_RECT_PLOT[:,:,0],X_RECT_PLOT[:,:,1],c='b')
plt.show()