Skip to main content
 首页 » 编程设计

python之像 plt.matshow 但有三角形的东西

2025年02月15日8zhujiabin

基本上,我想制作类似下面的东西(三角形而不是通常用于 plt.matshow 的正方形)。

可以从四个二维数组开始,每个数组代表一组三角形的颜色值:右、左、下、上:

import numpy as np 
right=np.random.randn(8, 8) 
left=np.random.randn(8, 8) 
bottom=np.random.randn(8, 8) 
top=np.random.randn(8, 8) 

但我对阴谋一无所知......

请您参考如下方法:

您确实可以使用 tripcolor 来绘制一组三角形。在下面的代码中,函数 quatromatrix 将 4 个二维数组值作为输入作为输入,创建三角形并重新排列颜色以适合各自的位置。因此,它非常类似于绘制 4 个 imshow 图。

import matplotlib.pyplot as plt 
import numpy as np 
 
def quatromatrix(left, bottom, right, top, ax=None, triplotkw={},tripcolorkw={}): 
    if not ax: ax=plt.gca() 
    n = left.shape[0]; m=left.shape[1] 
 
    a = np.array([[0,0],[0,1],[.5,.5],[1,0],[1,1]]) 
    tr = np.array([[0,1,2], [0,2,3],[2,3,4],[1,2,4]]) 
 
    A = np.zeros((n*m*5,2)) 
    Tr = np.zeros((n*m*4,3)) 
 
    for i in range(n): 
        for j in range(m): 
            k = i*m+j 
            A[k*5:(k+1)*5,:] = np.c_[a[:,0]+j, a[:,1]+i] 
            Tr[k*4:(k+1)*4,:] = tr + k*5 
 
    C = np.c_[ left.flatten(), bottom.flatten(),  
              right.flatten(), top.flatten()   ].flatten() 
 
    triplot = ax.triplot(A[:,0], A[:,1], Tr, **triplotkw) 
    tripcolor = ax.tripcolor(A[:,0], A[:,1], Tr, facecolors=C, **tripcolorkw) 
    return tripcolor 
 
 
right=np.random.randn(8, 8) 
left=np.random.randn(8, 8) 
bottom=np.random.randn(8, 8) 
top=np.random.randn(8, 8) 
 
fig, ax=plt.subplots() 
 
quatromatrix(left, bottom, right, top, ax=ax, 
             triplotkw={"color":"k", "lw":1}, 
             tripcolorkw={"cmap": "plasma"})  
 
ax.margins(0) 
ax.set_aspect("equal")