Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

python - Add a legend in a 3D scatterplot with scatter() in Matplotlib

I want to create a 3D scatterplot with different datasets in the same plot and a legend with their labels. The problem I am facing is that I cannot properly add the legend and I get a plot with an empty label as the figure in:

http://tinypic.com/view.php?pic=4jnm83&s=5#.Uqd-05GP-gQ.

More specifically, I get the error:

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

Please find below an example demo of what I have tried so far:

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

I have seen other roughly similar examples but none of them uses the scatter() plot. Apart from a working solution, can someone explain what am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)

The problem is that the legend function don't support the type returned by a 3D scatter. So you have to create a "dummy plot" with the same characteristics and put those in the legend.

numpoints = 1 to get only one dot in the legend
linestyle= "none" So there is no line drawn in the legend


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...