我有一个带有 n 个顶点的二维三角形网格,它存储在变量 tri(一个 matplotlib.tri.Triangulation 对象)中;我可以很容易地使用 matplotlib 的 tripcolor 函数绘制网格,并且一切正常。但是,每个顶点 (vcolors) 我也有 (r,g,b) 三元组,并且这些值不沿单个维度下降,因此不能轻易转换为颜色图(例如,想象一下,如果您在一张公园的大照片上叠加一个三角形网格,然后为每个顶点分配其下方像素的颜色)。
我以为我可以做这样的事情:
matplotlib.pyplot.tripcolor(tri, vcolors)
ValueError: Collections can only map rank 1 arrays
有没有一种方便的方法可以将类似 vcolors 的 (n x 3) 矩阵转换为 tripcolor 可用的矩阵?是否有接受顶点颜色的 tripcolor 替代品?
我尝试过的一件事是制作我自己的颜色图:
z = numpy.asarray(range(len(vcolors)), dtype=np.float) / (len(vcolors) - 1)
cmap = matplotlib.colors.Colormap(vcolors, N=len(vcolors))
matplotlib.pyplot.tripcolor(tri, z, cmap=cmap)
matplotlib.pyplot.show()
然而,这什么也没做——没有数字出现,也没有引发错误;该函数返回一个图形句柄,但没有任何内容被渲染(我使用的是 IPython 笔记本)。请注意,如果我调用以下命令,则绘图显示得很好:
tripcolor(tri, np.zeros(len(vcolors)))
matplotlib.pyplot.show()
我正在使用 Python 2.7。
请您参考如下方法:
在深入了解 matplotlib 的 tripcolor 和 Colormap 代码后,我想到了以下解决方案,它似乎只能作为只要使用“gouraud”阴影(否则,它在推断面部颜色方面做得很差;见下文)。
诀窍是创建一个颜色图,当在 0 和 1(含)之间给定 n 均匀间隔的数字时,它会再现原始数组颜色:
def colors_to_cmap(colors):
'''
colors_to_cmap(nx3_or_nx4_rgba_array) yields a matplotlib colormap object that, when
that will reproduce the colors in the given array when passed a list of n evenly
spaced numbers between 0 and 1 (inclusive), where n is the length of the argument.
Example:
cmap = colors_to_cmap(colors)
zs = np.asarray(range(len(colors)), dtype=np.float) / (len(colors)-1)
# cmap(zs) should reproduce colors; cmap[zs[i]] == colors[i]
'''
colors = np.asarray(colors)
if colors.shape[1] == 3:
colors = np.hstack((colors, np.ones((len(colors),1))))
steps = (0.5 + np.asarray(range(len(colors)-1), dtype=np.float))/(len(colors) - 1)
return matplotlib.colors.LinearSegmentedColormap(
'auto_cmap',
{clrname: ([(0, col[0], col[0])] +
[(step, c0, c1) for (step,c0,c1) in zip(steps, col[:-1], col[1:])] +
[(1, col[-1], col[-1])])
for (clridx,clrname) in enumerate(['red', 'green', 'blue', 'alpha'])
for col in [colors[:,clridx]]},
N=len(colors))
再次请注意,'gouraud' 着色是实现此功能所必需的。为了演示失败的原因,以下代码块显示了我的特定用例。 (我正在绘制带有部分透明数据覆盖层的扁平皮质表的一部分)。在这段代码中,有 40,886 个顶点(在 the_map.coordinates 中)和 81,126 个三角形(在 the_map.indexed_faces 中); colors 数组的形状为 (40886, 3)。
以下代码适用于“gouraud”着色:
tri = matplotlib.tri.Triangulation(the_map.coordinates[0],
the_map.coordinates[1],
triangles=the_map.indexed_faces.T)
cmap = rgbs_to_cmap(colors)
zs = np.asarray(range(the_map.vertex_count), dtype=np.float) / (the_map.vertex_count - 1)
plt.figure(figsize=(16,16))
plt.tripcolor(tri, zs, cmap=cmap, shading='gouraud')
但如果没有 'gouraud' 着色,面部颜色可能是根据顶点的平均值分配的(尚未验证),这显然是错误的:
plt.figure(figsize=(16,16))
plt.tripcolor(tri, zs, cmap=cmap)
