【问题标题】:Filling triangles in Matplotlib triplot with individual colors用单独的颜色填充 Matplotlib triplot 中的三角形
【发布时间】:2015-03-30 11:39:36
【问题描述】:

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

【问题讨论】:

    标签: python matplotlib delaunay


    【解决方案1】:

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

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

    下一个参数必须是 C,颜色值数组,或者 如果颜色值定义在 点,或者如果颜色值,则在三角剖分中每个三角形一个 在三角形处定义。如果点数相同 和三角剖分中的三角形假定颜色 值在点处定义;强制使用颜色值 三角形使用 kwarg facecolors=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()
    

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

    【讨论】:

      猜你喜欢
      • 2017-08-05
      • 2016-03-13
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多