类似于plt.matshow但带有三角形 [英] something like plt.matshow but with triangles

查看:126
本文介绍了类似于plt.matshow但带有三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想做类似以下的事情(三角形不是正方形,通常与plt.matshow一起使用).

Basically, I'd like to make something like the following (triangles not squares as is typically used with plt.matshow).

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

One could start with four 2D arrays, each representing the values for the colours of a set of triangles: right, left, bottom, top:

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)

但是我不知道要密谋...

But I have no idea about the plotting...

推荐答案

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

You may indeed use tripcolor to plot a set of triangles. In the code below the function quatromatrix takes 4 2D arrays of values to colormap as input, creates the triangles and rearanges the colors to fit to the respective positions. It is thus very similar to plotting 4 imshow plots.

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")

这篇关于类似于plt.matshow但带有三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆