使用颜色渐变在3D matplolib图中填充三角形

时间:2017-02-13 21:01:09

标签: python matplotlib polygon

我正在尝试将色彩映射应用于3d多边形。 多边形很好,显示在正确的位置。 我唯一能做的就是用渐变填充它。

这是我的代码:

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

有人可以帮助我吗?

修改

此外,渐变应该看起来像this

1 个答案:

答案 0 :(得分:0)

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

获取三角形渐变的一种方法是使用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()

enter image description here

在这里,使用contourf有点像黑客。为了在某​​个其他方向上获得梯度,最好使用曲面图(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,但这也可能会显着增加绘图时间。

enter image description here

相关问题