如何在 matplotlib 中为 3D 条形图创建图例?
Posted
技术标签:
【中文标题】如何在 matplotlib 中为 3D 条形图创建图例?【英文标题】:How to create a legend for 3D bar in matplotlib? 【发布时间】:2011-08-13 18:23:04 【问题描述】:给定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. "
【问题讨论】:
【参考方案1】:您需要在不支持图例的情况下使用proxy artist。
这段代码:
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()
产生这个:
【讨论】:
你也知道如何用曲面图来做吗? @CharlieParker 它应该适用于任何情节。也许您想要colorbar
而不是标准图例?以上是关于如何在 matplotlib 中为 3D 条形图创建图例?的主要内容,如果未能解决你的问题,请参考以下文章
在 Pandas v0.20 和 matplotlib 中为条形分配颜色的问题
Python matplotlib可视化:在Matplotlib中为坐标轴刻度添加自定义符号(例如,货币符号¥$等)水平条形图(horizontal bar)