使用Matplotlib中的scatter()在三维散点图中添加图例

2024-06-28 18:48:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个三维散点图,在同一个图中包含不同的数据集,以及一个带有标签的图例。我面临的问题是,我无法正确添加图例,并且我得到了一个带有空标签的绘图,如图中所示:

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()图。除了一个可行的解决方案,有人能解释我做错了什么吗?


Tags: fromimportrangepltrandom标签axx1
1条回答
网友
1楼 · 发布于 2024-06-28 18:48:45
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)

问题是legend函数不支持3D散点返回的类型。所以你必须创建一个具有相同特征的“虚拟情节”,并将其放入传说中。

numpoints=1在图例中只得到一个点
linestyle=“none”因此图例中没有绘制线

相关问题 更多 >