gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:16:49 30 4
gpt4 key购买 nike

是否可以使用 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com