用颜色渐变填充3D Matplolib图中的三角形 [英] Fill a triangle in 3D matplolib plot with a color gradient

查看:100
本文介绍了用颜色渐变填充3D Matplolib图中的三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将颜色贴图应用于3d多边形. 多边形很好,显示在正确的位置. 我唯一不能做的就是用渐变填充它.

I am trying to apply a colormap to a 3d Polygon. The polygon is fine, shows up in the correct position. The only thing I can't do is filling it with a gradient.

这是我的代码:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import LinearSegmentedColormap
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

fig = plt.figure()
ax = Axes3D(fig)

x = [0,0,0]
y = [0,1,0]
z = [0,0,1]
verts = [zip(x, y,z)] #(0,0,0) (0,1,0) (0,0,1)

colors = ['red', 'gray', 'gray', 'green']
index  = [0.0, 0.49, 0.509, 1.0]
cm = LinearSegmentedColormap.from_list('my_colormap', zip(index, colors))

collection = Poly3DCollection(verts, cmap=cm)
ax.add_collection3d(collection)
plt.show()

请问有人可以帮我吗?

此外,渐变应类似于

推荐答案

由于集合的每个成员只能具有与之关联的单一颜色,因此不能简单地使用三角形来实现渐变填充.

Since every member of a collection can only have a single color associated with it, you cannot simply use a triangle to achieve a gradient fill.

获得三角形渐变的一种方法是使用plt.contourf.

One way of obtaining a gradient in a triangle is to use plt.contourf.

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

X, Y = np.meshgrid(np.linspace(0,1), np.linspace(0,1)) 
Z = 1.-X-Y
Z[Z<0] = 0

cset = ax.contourf(X, Y, Z, zdir='x', levels=np.linspace(0,1),offset=0, cmap=plt.cm.jet)
ax.set_xlabel('X')
ax.set_xlim(0, 1)
ax.set_ylabel('Y')
ax.set_ylim(0,1)
ax.set_zlabel('Z')
ax.set_zlim(0,1)    
plt.show()

在这里,contourf的使用有点麻烦.为了获得其他方向的梯度,最好使用表面图(plot_surface).

Here, the use of contourf is a bit of a hack. In order to obtain a gradient in some other direction it would probably be better to use a surface plot (plot_surface).

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
points=50
Y, Z = np.meshgrid(np.linspace(0,1,points), np.linspace(0,1,points)) 
Z = Z*(1-Y)
color =(1-Y+Z)*0.5

ax.plot_surface(np.zeros_like(Y), Y, Z, facecolors=plt.cm.jet(color), 
                rcount=points, ccount=points, shade=False)

ax.set_xlabel('X')
ax.set_xlim(0, 1)
ax.set_ylabel('Y')
ax.set_ylim(0,1)
ax.set_zlabel('Z')
ax.set_zlim(0,1)    
plt.show()

要获得更平滑的图像,可以增加points,但这也可能会显着增加绘制时间.

To obtain a smoother picture, you can increase points, but this may also increase drawing time significantly.

这篇关于用颜色渐变填充3D Matplolib图中的三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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