如何在matplotlib中为3D栏创建图例?

Alm*_*mad 17 python numpy graph matplotlib

鉴于ax = plt.subplot():

ax.bar()[0]可以传递给plt.legend().

但是,ax.bar3d()退货None.如何为显示的栏创建图例?

更新:

将legend ="stuff"传递给ax.bar3d()而不是调用ax.legend()加注

/usr/lib/python2.6/site-packages/matplotlib/axes.py:4368: UserWarning: No labeled objects found. Use label='...' kwarg on individual plots.
warnings.warn("No labeled objects found. "
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 19

您需要使用不支持图例的代理艺术家.

这段代码:

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4)

elements = (len(xedges) - 1) * (len(yedges) - 1)
xpos, ypos = np.meshgrid(xedges[:-1]+0.25, yedges[:-1]+0.25)

xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(elements)
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()

ax.bar3d(xpos[:8], ypos[:8], zpos[:8], dx, dy, dz, color='b', zsort='average')
blue_proxy = plt.Rectangle((0, 0), 1, 1, fc="b")
ax.bar3d(xpos[8:], ypos[8:], zpos[8:], dx, dy, dz, color='r', zsort='average')
red_proxy = plt.Rectangle((0, 0), 1, 1, fc="r")
ax.legend([blue_proxy,red_proxy],['cars','bikes'])

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

产生这个:在此输入图像描述