python - 用单独的颜色填充 Matplotlib triplot 中的三角形

标签 python matplotlib delaunay

是否可以使用 pyplot 的 triplot 函数绘制由 scipy.spatial.Delaunay 生成的三角形列表,以便可以绘制每个三角形并用单独的颜色填充?我创建的基本 python 脚本是

import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay
import matplotlib.image as mpimg  

h = 300
w = 1000

npts = 30

pts = np.zeros((npts,2))
pts[:,0] = np.random.randint(0,w,npts)
pts[:,1] = np.random.randint(0,h,npts)
tri = Delaunay(pts)

plt.xlim(0, w)
plt.ylim(0, h)

# Determine the color used for each triangle based upon the orthocenter
# of the triangle and the corresponding pixel color in a background image.

centers = np.sum(pts[tri.simplices], axis=1, dtype='int')/3.0
colors = [img[y,x] for x,y in centers]

# This plots the edges of each triangle with no fill. I'd like to 
# include the colors list to plot a fill for each.

plt.triplot(pts[:,0], pts[:,1], tri.simplices.copy())

plt.show()

triplot 是否有一些参数,我可以在其中传递包含相应三角形颜色的颜色列表。我确信我可以使用适当的填充颜色循环绘制每个三角形,但如果有更优雅、更快速的方法就好了。

最佳答案

您正在寻找的功能包含在 pyplot.tripcolor 中.

从它的文档中,您会发现它很“聪明”,并会尝试猜测您是否为点或三角形指定了颜色:

The next argument must be C, the array of color values, either one per point in the triangulation if color values are defined at points, or one per triangle in the triangulation if color values are defined at triangles. If there are the same number of points and triangles in the triangulation it is assumed that color values are defined at points; to force the use of color values at triangles use the kwarg facecolors=C instead of just C.

继续你的例子:

import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay

h = 300
w = 1000
npts = 500
pts = np.zeros((npts,2))
pts[:,0] = np.random.randint(0,w,npts)
pts[:,1] = np.random.randint(0,h,npts)
tri = Delaunay(pts)
plt.xlim(0, w)
plt.ylim(0, h)
centers = np.sum(pts[tri.simplices], axis=1, dtype='int')/3.0
colors = np.array([ (x-w/2.)**2 + (y-h/2.)**2 for x,y in centers])
plt.tripcolor(pts[:,0], pts[:,1], tri.simplices.copy(), facecolors=colors, edgecolors='k')
plt.gca().set_aspect('equal')
plt.show()

这里我只是根据三角形中心和图像中心之间的距离来设置颜色(因为我没有合适的图像)。

enter image description here

关于python - 用单独的颜色填充 Matplotlib triplot 中的三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28245327/

相关文章:

python - Django 更新而不是插入新记录

python - 如何将 Flask 路由中的 PATCH 方法作为 API 处理?

python - 有没有一种简单的方法可以根据 .gitignore 规则匹配文件?

python - 无法重置轴

algorithm - Bowyer-Watson 算法 : how to fill "holes" left by removing triangles with super triangle vertices

python - 在 Django 项目中哪里安全地存储 Google_Application_Credentials?

python - 使用 python 中的 matplotlib 制作具有指定离散颜色映射的热图

python - matplotlib 更改现有 skimage 图上的线宽

python scipy Delaunay 绘图点云

parallel-processing - 平行Delaunay三角剖分