【发布时间】:2020-03-30 21:06:51
【问题描述】:
我创建了一个散点图,其中的点随表内某些大小的行星而变化。 为此,我使用了这个函数:
#data:
x=composition
y=composition
z=planetary_radii
#some stuff to let the scatter organized:
left, width = 0.1, 0.7
bottom, height = 0.1, 0.7
rect_scatter = [left, bottom, width, height]
ax_scatter = plt.axes(rect_scatter)
#the function that separates the dots in different colors:
colors = []
for i in z:
if i > 8:
colors.append('r')
elif i<8 and i>4:
colors.append('b')
elif i<4 and i>2:
colors.append('g')
elif i<2:
colors.append('orange')
else:
colors.append('y')
# the scatter plot:
ax_scatter.scatter(x, y,c=colors, s=10)
然后,我希望这些点位于标签中,但名称不同于“g”、“orange”等。它们会像“Radii>8”、“4”
我怎样才能做到这一点?我是否必须创建另一个函数才能使用 db.scatter 中的标签参数?
这张图片显示了没有标签的散点图:
【问题讨论】:
-
将您的数据拆分为列表。然后单独绘制列表
plt.plot( a, ..., label = 'a')(您可以选择颜色),或者如果您在循环中有很多plt.plot( aa[i], ..., label = label[i]),其中 label[i] 是标签列表。 (颜色将是自动的,或者您可以使用要在循环中分配的颜色列表)。然后添加一行plt.legend() -
最新的matplotlib版本(3.1)可以做到这一点:matplotlib.org/3.1.0/gallery/lines_bars_and_markers/…
-
@Solvalou 我试过使用这个函数:
legend1 = ax_scatter.legend(*scatter.legend_elements(), loc="lower right", title="Classes") ax_scatter.add_artist(legend1)但我收到以下错误消息:'PathCollection' 对象没有属性'legend_elements'。如何应对? -
这可能是因为您使用的是旧版本的
matplotlib,因为只有最新版本才支持此功能!
标签: python matplotlib scatter-plot