Visualization with Python - matplotlib ③¶
matplotlib ③¶
이번 포스팅에서는 matplotlib의 triangular grid 사용법에 대해 알아 보자.¶
- triangular grid를 사용하연 기존의 사각형 영역 뿐 아니라 임의의 영역에 대해서 컨투어 플롯이나 서피스 플롯을 그릴 수 있다.
- 그러므로 정의역(domain)이 아닌 2차원 함수를 시각화하는데 많이 사용된다.
In [1]:
import numpy as np
import matplotlib as mpl
import matplotlib.pylab as plt
import matplotlib.tri as mtri
%matplotlib inline
삼각 그리드 클래스¶
삼각 그리드 생성
삼각 그리드 플롯
triplot
tricontour
tricontourf
tripcolor
삼각 그리드 보간
TriInterpolator
LinearTriInterpolator
CubicTriInterpolator
삼각 그리드 생성¶
- 삼각 그리드는
Triangulation
클래스로 생성한다. Triangulation
는x
,y
,triangles
세 개의 인수를 받는다.x
,y
는 일련의 점들의 x좌표와 y좌표를 나타내는 1차원 벡터triangles
는 이 점들에 대한 기하학적 위상 정보 즉, 어떤 삼각형이 있으며 각 삼각형이 어떤 점들로 이루어져있는가를 보인다.- 만약
triangles
가 주어지지 않으면 자동으로 생성한다.
In [2]:
x = np.asarray([0, 1, 2])
y = np.asarray([0, np.sqrt(3), 0])
# 삼각 그리드 생성
triangles = [[0, 1, 2]]
triang = mtri.Triangulation(x, y, triangles)
plt.triplot(triang, 'ko-')
plt.xlim(-0.1, 2.1)
plt.ylim(-0.1, 1.8)
plt.show()
In [3]:
x = np.asarray([0, 1, 2, 3, 4, 2])
y = np.asarray([0, np.sqrt(3), 0, np.sqrt(3), 0, 2*np.sqrt(3)])
triangles = [[0, 1, 2], [2, 3, 4], [1, 2, 3], [1, 3, 5]]
triang = mtri.Triangulation(x, y, triangles)
plt.triplot(triang, 'ko-')
plt.xlim(-0.1, 4.1)
plt.ylim(-0.1, 3.7)
plt.show()
grid 세분화¶
- 그리드를 더 세분화하려면
TriRefiner
또는UniformTriRefiner
를 사용한다. 이 클래스들은 다음과 같은 메서드를 가진다.
refine_triangulation
: 단순히 삼각 그리드를 세분화
refine_field
: 실제 함수 값에 대해 최적화된 삼각 그리드 생성
In [4]:
refiner = mtri.UniformTriRefiner(triang)
triang2 = refiner.refine_triangulation(subdiv=2)
plt.triplot(triang2, 'ko-')
plt.xlim(-0.1, 4.1)
plt.ylim(-0.1, 3.7)
plt.show()
grid plot¶
In [5]:
triang5 = refiner.refine_triangulation(subdiv=5)
z5 = np.cos(1.5*triang5.x)*np.cos(1.5*triang5.y)
plt.tricontourf(triang5, z5)
plt.show()
In [6]:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
triang3 = refiner.refine_triangulation(subdiv=3)
z3 = np.cos(1.5 * triang3.x) * np.cos(1.5 * triang3.y)
fig = plt.figure(figsize=(12,8))
ax = fig.gca(projection='3d')
ax.plot_trisurf(triang3.x, triang3.y, z3, cmap=cm.jet, linewidth=0.2)
ax.tricontourf(triang3, z3, zdir='z', offset=-1.2, cmap=cm.coolwarm)
ax.set_zlim(-1, 1)
ax.view_init(40, -40)
plt.show()