I'm trying to plot 3d boxes iteratively using matplot and I want to add a legend for each box
def add_box(...):
# Draw 6 Faces of a box
...
...
xx, xy, xz = np.meshgrid(x_range, y_range, z_range) # X
yy, yx, yz = np.meshgrid(y_range, x_range, z_range) # Y
zx, zz, zy = np.meshgrid(x_range, z_range, y_range) # Z
for i in range(2):
self.ax.plot_wireframe(xx[i], xy[i], xz[i], color=color)
self.ax.plot_surface(xx[i], xy[i], xz[i], color=color, alpha=self.alpha)
self.ax.plot_wireframe(yx[i], yy[i], yz[i], color=color)
self.ax.plot_surface(yx[i], yy[i], yz[i], color=color, alpha=self.alpha)
self.ax.plot_wireframe(zx[i], zy[i], zz[i], color=color)
self.ax.plot_surface(zx[i], zy[i], zz[i], color=color, alpha=self.alpha)
# Creating dummy plot for the legend
fake2Dline = mpl.lines.Line2D([0],[0], linestyle="none", c=color, marker = 'o')
self.fake2Dline.append(fake2Dline)
label_box = 'C1'
self.legend_label.append(label_box)
Calling legend function after looping over boxes done
def draw_legend(self):
self.ax.legend([self.fake2Dline], [self.legend_label], numpoints = 1, bbox_to_anchor=(1.04, 0.5), loc="upper left", fontsize=9)
The plot is working fine but no legend appears with the following error:
A proxy artist may be used instead.
I tried also to modify the dummy plot line to be:
# assign label in lines.Line2D
fake2Dline = mpl.lines.Line2D([0],[0], linestyle="none", c=color, marker = 'o', label='test1')
And then the legend function:
def draw_legend(self):
plt.legend([self.fake2Dline], numpoints = 1, bbox_to_anchor=(1.04, 0.5), loc="upper left", fontsize=9)
but the legend looked like that..
CodePudding user response:
legend
takes as 1st and 2nd argument a list of artists and a list of strings, respectively. You were passing lists of lists.
So is must be:
def draw_legend(self):
self.ax.legend(self.fake2Dline, self.legend_label, numpoints = 1, bbox_to_anchor=(1.04, 0.5), loc="upper left", fontsize=9)
PS: to prevent such kind of mistakes it might be better to use the plural form for the variable names (self.fake2Dlines
, self.legend_labels
)