PyPlot 图例:'Poly3DCollection' 对象没有属性“_edgecolors2d”

PyPlot legend: 'Poly3DCollection' object has no attribute '_edgecolors2d'

在我取消注释 plt.legend() 行之前,以下代码片段工作正常:

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

x = np.linspace(-1, 1)
y = np.linspace(-1, 1)
X, Y = np.meshgrid(x, y)
Z = np.sqrt(X**2 * Y)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, label='h=0')
ax.plot(np.zeros_like(y), y, np.zeros_like(y), label='singular points')
# plt.legend()
plt.show()

我收到以下错误: 'Poly3DCollection' object has no attribute '_edgecolors2d'

我认为原因可能是我在 2d 绘图中使用了 plt.legend() 的 framealphaframeon 参数,但我重新启动了运行时(我我正在 Google Colab Jupyter Notebook 中工作),清除所有变量,问题仍然存在。

可能导致此错误的原因是什么?

您好,我发现这是一个错误,库开发人员仍在努力解决它。 我在 git

中找到了有关该问题的以下线程

他们给出的建议是拿到密谋

surf = ax.plot_surface(X, Y, Z, label='h=0')
surf._facecolors2d=surf._facecolors3d
surf._edgecolors2d=surf._edgecolors3d

如果matplotlib版本是matplotlib 3.3.3 试试下面

surf._facecolors2d = surf._facecolor3d
surf._edgecolors2d = surf._edgecolor3d

更新@AmilaMGunawardana 的回答

matplotlib 3.3.3 起,_facecolors3d_edgecolors3d 不存在。所以,而不是这个:

surf._facecolors2d = surf._facecolors3d
surf._edgecolors2d = surf._edgecolors3d

这会导致类似的 AttributeError,试试这个:

surf._facecolors2d = surf._facecolor3d
surf._edgecolors2d = surf._edgecolor3d

由于代表率低,我不得不将其作为答案而不是评论。

ax._facecolors2d = ax._facecolor

在 Matplotlib 3.3.4 中为我工作。

我正在使用 matplotlib 3.5,这对我有用:

surf._facecolors2d = surf._facecolor3d
surf._edgecolors2d = surf._edgecolor3d