我创建了一个散点图,该散点图的点随表中行星的某些尺寸而变化。 为此,我使用了以下功能:
#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中使用label参数?
此图显示了没有标签的散点图:
答案 0 :(得分:1)
我得到了一个使用matplotlib
最新版本3.1.2的解决方案。要安装它,执行
pip install -U matplotlib
但是请注意,它仅适用于Python3,因为Python2在版本2之前仅支持matplotlib
。
在此处查看完整的代码:
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
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 classes:
classes = np.zeros( len(x) ) # z > 8
classes[(z <= 8) & (z > 4)] = 1
classes[(z <= 4) & (z > 2)] = 2
classes[z <= 2] = 3
# create color map:
colors = ['r', 'b', 'g', 'orange', 'y']
cm = LinearSegmentedColormap.from_list('custom', colors, N=len(colors))
# the scatter plot:
scatter = ax_scatter.scatter(x, y, c=classes, s=10, cmap=cm)
lines, labels = scatter.legend_elements()
# legend with custom labels
labels = [r'Radii $> 8$', r'$4 <$ Radii $\leq 8$',
r'$2 <$ Radii $\leq 4$', r'Radii $\leq 2$']
legend = ax_scatter.legend(lines, labels,
loc="lower right", title="Classes")
ax_scatter.add_artist(legend)
plt.show()
根据z
的值定义了四个类。请注意,由于您排除了一些值(例如4和8),因此我使用了小于等号稍微更改了范围。然后,定义一个自定义颜色图,在其中设置对应类别的颜色。将结果提供给散点图,通过调用lines
从中得出labels
和legend_elements()
。现在,您可以根据需要更改这些标签,最后将它们提供给ax_scatter.legend()
。在这里,您还可以指定图例的标题。
答案 1 :(得分:0)
基于roadrunner66的评论,另一种方法也可以在Python2.7中使用:
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
x = np.asarray(composition)
y = np.asarray(composition)
z = np.asarray(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)
# definition of filters, colors, and labels
filters = [z > 8, (z <= 8) & (z > 4), (z <= 4) & (z > 2), z <= 2]
colors = ['r', 'b', 'g', 'orange', 'y']
labels = ['Radii $> 8$', r'$4 <$ Radii $\leq 8$',
r'$2 <$ Radii $\leq 4$', r'Radii $\leq 2$']
# filter the data and plot:
for idx, f in enumerate(filters):
ax_scatter.scatter(x[f], y[f],
c=colors[idx], s=10, label=labels[idx])
ax_scatter.legend(title='Classes', loc="lower right")
plt.show()
首先请确保您的数据存储在np.array
中。您可以根据需要设置filters
,colors
和labels
。然后,使用先前定义的过滤条件过滤数据并绘制图表。在这里,将应用指定的colors
和labels
。