在Matplotlib中使用scatter()函数制作3D散点图时,如何添加图例?

8
我想创建一个3D散点图,将不同数据集放在同一个图中,并使用标签来表示它们。我面临的问题是无法正确添加图例,导致出现空标签的图形,就像这张图片一样:http://tinypic.com/view.php?pic=4jnm83&s=5#.Uqd-05GP-gQ
更具体地说,我遇到了以下错误:
/usr/lib/pymodules/python2.7/matplotlib/legend.py:610: UserWarning: Legend does not support <mpl_toolkits.mplot3d.art3d.Patch3DCollection object at 0x3bf46d0>
Use proxy artist instead."

请查看下面一个我尝试过的示例演示:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random
import csv
from os import listdir
from os.path import isfile, join

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

handles = []
colors = ['blue', 'red']

X1 = range(0,10)
Y1 = range(0,10)
Z1 = range(0,10)

random.shuffle(X1)
random.shuffle(Y1)
random.shuffle(Z1)

scatter1 = ax.scatter(X1, Y1, Z1, c = colors[0], marker = 'o')

random.shuffle(X1)
random.shuffle(Y1)
random.shuffle(Z1)

scatter2 = ax.scatter(X1, Y1, Z1, c = colors[1], marker = 'v')

ax.set_xlabel('X', fontsize = 10)
ax.set_ylabel('Y', fontsize = 10)
ax.set_zlabel('Z', fontsize = 10)

ax.legend([scatter1, scatter2], ['label1', 'label2'])

plt.show()

我看过其他类似的例子,但它们都没有使用scatter()图。除了一个可行的解决方案外,有人能解释一下我错在哪里吗?


你看了关于代理艺术家的错误信息中指定的链接吗? - M4rtini
是的,但由于我刚接触Python,错误的原因对我来说并不清楚。 - Dio
这篇文章相当古老。请注意,在当前版本的matplotlib中,图例的代码可以正常工作。 - JohanC
1个回答

18
scatter1_proxy = matplotlib.lines.Line2D([0],[0], linestyle="none", c=colors[0], marker = 'o')
scatter2_proxy = matplotlib.lines.Line2D([0],[0], linestyle="none", c=colors[1], marker = 'v')
ax.legend([scatter1_proxy, scatter2_proxy], ['label1', 'label2'], numpoints = 1)
问题在于图例功能不支持3D散点图返回的类型。因此,您必须创建具有相同特征的“虚拟图”,并将其放在图例中。
numpoints = 1以在图例中仅获取一个点
linestyle= "none"以便在图例中不画线。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接