Fill a triangle in 3D matplolib plot with a color gradient

 ̄綄美尐妖づ 提交于 2019-12-23 06:08:35

问题


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.

Here is my code:

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

Can someone help me, please?

EDIT:

Moreover the gradient should look like this


回答1:


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.

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

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

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



来源:https://stackoverflow.com/questions/42213466/fill-a-triangle-in-3d-matplolib-plot-with-a-color-gradient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!