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

siz*_*erz 2 python delaunay matplotlib

是否可以使用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()
Run Code Online (Sandbox Code Playgroud)

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

Oli*_* W. 6

您正在寻找的功能包括在内pyplot.tripcolor.

从它的文档中,你会看到它是"聪明的"并试图猜测你是否为点或三角形指定了颜色:

下一个参数必须是C,颜色值数组,如果在点处定义颜色值,则在三角测量中每个点一个,或者如果在三角形中定义颜色值,则在三角测量中每个三角形一个.如果在三角测量中存在相同数量的点和三角形,则假设颜色值在点处定义; 迫使在三角形用色值的使用kwarg facecolors = 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()
Run Code Online (Sandbox Code Playgroud)

这里我只是将颜色基于三角形中心和图像中心之间的距离(因为我没有合适的图像).

在此输入图像描述