matplotlib中Poly3DCollection图的透明度

Chi*_*ler 11 python transparency matplotlib scatter-plot

我试图用Python的神话般的Matplotlib包绘制一些对象.这些对象包括用它们实现的点plt.scatter()和用它们实现的补丁Poly3DCollection.我想让贴片具有轻微的透明度,以便可以看到贴片后面的点和边缘.

这里是我已经生成的代码和图.似乎我几乎在那里,只是缺少透明度的特征.有趣的是,如果我首先绘制点Ploy3DCollection和之后的scatter点,可以看到点,但不是边缘.

有人对我提出建议吗?

在此输入图像描述

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = [0, 2, 1, 1]
y = [0, 0, 1, 0]
z = [0, 0, 0, 1]

vertices = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]

tupleList = list(zip(x, y, z))

poly3d = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))] for ix in range(len(vertices))]
ax.scatter(x,y,z)
ax.add_collection3d(Poly3DCollection(poly3d, facecolors='w', linewidths=1, alpha=0.5))

plt.show()
Run Code Online (Sandbox Code Playgroud)

小智 13

我对OP代码做了一些修改,并使透明度有效.似乎Poly3DCollection的facecolors参数会覆盖透明度参数,因此解决方案是将颜色设置为单独调用Poly3DCollection.set_color或者Poly3DCollection.set_facecolor:

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = [0, 2, 1, 1]
y = [0, 0, 1, 0]
z = [0, 0, 0, 1]

vertices = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]

tupleList = zip(x, y, z)

poly3d = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))] for ix in range(len(vertices))]
ax.scatter(x,y,z)
collection = Poly3DCollection(poly3d, linewidths=1, alpha=0.2)
face_color = [0.5, 0.5, 1] # alternative: matplotlib.colors.rgb2hex([0.5, 0.5, 1])
collection.set_facecolor(face_color)
ax.add_collection3d(collection)

plt.show()
Run Code Online (Sandbox Code Playgroud)

有趣的是,如果您明确设置边缘颜色collection.set_edgecolor('k'),边缘也将遵循透明度设置.


Chi*_*ler 8

我找到了一个很好的解决方法:在绘制数据之后,在顶部做另一个绘图,颜色相同,线条样式更轻.而不是Poly3DCollection我使用Line3DCollection,所以没有绘制面.结果看起来非常符合预期.

请参阅下面的新图和创建它的脚本.

在此输入图像描述

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = [0, 2, 1, 1]
y = [0, 0, 1, 0]
z = [0, 0, 0, 1]

vertices = [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]

tupleList = list(zip(x, y, z))

poly3d = [[tupleList[vertices[ix][iy]] for iy in range(len(vertices[0]))] for ix in range(len(vertices))]
ax.scatter(x,y,z)
ax.add_collection3d(Poly3DCollection(poly3d, facecolors='w', linewidths=1, alpha=0.5))
ax.add_collection3d(Line3DCollection(poly3d, colors='k', linewidths=0.2, linestyles=':'))

plt.show()
Run Code Online (Sandbox Code Playgroud)