Python 在Matplotlib triplot中用单独的颜色填充三角形

Python 在Matplotlib triplot中用单独的颜色填充三角形,python,matplotlib,delaunay,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 =

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

您正在寻找的功能包含在中

从它的文档中,您将看到它是“智能”的,并尝试猜测您是否为点或三角形指定了颜色:

下一个参数必须是C,也就是颜色值的数组 如果颜色值是在以下位置定义的,则三角剖分中的每个点一个 点,或者如果颜色值为,则在三角剖分中每个三角形一个点 定义为三角形。如果分数相同 三角形在三角剖分中,假设颜色 在点上定义值;强制在以下位置使用颜色值的步骤 三角形使用kwarg FaceColor=C,而不仅仅是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()
在这里,我仅仅根据三角形中心和图像中心之间的距离来确定颜色(因为我没有合适的图像)