Creating a Triangulation for use in Matplotlib's plot_trisurf with matplotlib.tri.Triangulation

早过忘川 提交于 2019-12-02 11:37:04

There is an example on the matplotlib page that shows how to use points and triangles to create a matplotlib.tri.Triangulation. As this may be unnecessarily complicated, we may simplify even further.

Let's take 4 points, which should create 2 triangles. The triangles argument would specify the corners of the triangles in form of the indices of the points. As the documentation says,

triangles : integer array_like of shape (ntri, 3), optional
For each triangle, the indices of the three points that make up the triangle, ordered in an anticlockwise manner. [..]

Consider this code, where we have a (4,2) array, specifying the point coordinates, having the x and y coordinates for each point in a row. We then create triangles from them by using the indizes of the points that should constitute the triangle in an anti-clockwise manner.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri

xy = [[0.3,0.5],
      [0.6,0.8],
      [0.5,0.1],
      [0.1,0.2]]
xy = np.array(xy)

triangles = [[0,2,1],
             [2,0,3]]

triang = mtri.Triangulation(xy[:,0], xy[:,1], triangles=triangles)
plt.triplot(triang, marker="o")

plt.show()

The first triangle is made up of points 0, 2, 1 and the second of 2,0,3. The following graphics shows visualizes that code.

We may then create a list of z values and plot the same in 3D.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
from mpl_toolkits.mplot3d import Axes3D

xy = [[0.3,0.5],
      [0.6,0.8],
      [0.5,0.1],
      [0.1,0.2]]
xy = np.array(xy)

triangles = [[0,2,1],
             [2,0,3]]

triang = mtri.Triangulation(xy[:,0], xy[:,1], triangles=triangles)

z = [0.1,0.2,0.3,0.4]

fig, ax = plt.subplots(subplot_kw =dict(projection="3d"))
ax.plot_trisurf(triang, z)

plt.show()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!