如何为 3D 栏创建图例

2024-01-15

Given ax = plt.subplot():

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

然而,ax.bar3d()回报None。如何为显示的栏创建图例?

UPDATE:

将 legend="stuff" 传递给ax.bar3d()而不是打电话ax.legend() raises

/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. "

你需要使用一个代理艺术家 https://matplotlib.org/stable/tutorials/intermediate/legend_guide.html#creating-artists-specifically-for-adding-to-the-legend-aka-proxy-artists不支持图例的地方。

这段代码:

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

produces this:enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 3D 栏创建图例 的相关文章

随机推荐