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

Question:

The following code snippet works fine until I uncomment the plt.legend() line:

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

I get the following error:
'Poly3DCollection' object has no attribute '_edgecolors2d'

I thought the cause may have been that I had played around with the framealpha and frameon parameters of plt.legend() in 2d plots, but I restarted the runtime (I’m working in a Google Colab Jupyter Notebook), clearing all variables, and the problem persisted.

What might be causing this error?

Asked By: Jacob Stern

||

Answers:

Hi I found that is a bug still the library developers are trying to figure out it.
I have found the following thread about the issue in git

Their suggestion they have given is to get the plotting

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

If the matplotlib version is matplotlib 3.3.3 try below

surf._facecolors2d = surf._facecolor3d
surf._edgecolors2d = surf._edgecolor3d
Answered By: AmilaMGunawardana

Update to @AmilaMGunawardana’s answer

As of matplotlib 3.3.3, _facecolors3d and _edgecolors3d do not exist. So, instead of this:

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

that would lead to a similar AttributeError, try this:

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

I had to make this an answer, instead of a comment, due to low rep.

Answered By: P_0
ax._facecolors2d = ax._facecolor

is working for me in Matplotlib 3.3.4.

Answered By: Rexcirus

I am on matplotlib 3.5 and this worked for me:

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

This works for me : try to replace both face and edge 2d to 3d

plt.figure()
surf = ssr2D.T.plot.surface(label="ssr")
surf._facecolors2d  = surf._facecolor3d
surf._edgecolors2d  = surf._edgecolor3d
plt.legend()
plt.show()
Answered By: hossein nhk
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.