如何为matplotlib散点图添加单独标签?
我正在使用matplotlib做散点图,但我找不到给点加标签的方法。例如:
scatter1=plt.scatter(data1["x"], data1["y"], marker="o",
c="blue",
facecolors="white",
edgecolors="blue")
我希望“y”中的点能有标签,比如“点1”、“点2”等等。但我搞不明白怎么做。
2 个回答
0
另一个选择是使用 plt.text。下面是一个可以重复的例子:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(20)
N = 5
X=np.random.randint(10, size=(N))
Y=np.random.randint(10, size=(N))
data = np.random.random((N, 4))
annotations= ['point {0}'.format(i) for i in range(N)]
plt.figure(figsize=(8,6))
plt.scatter(X, Y, s=100, color = "blue")
plt.xlabel("X")
plt.ylabel("Y")
for i, label in enumerate(annotations):
plt.text(X[i]-0.6, Y[i]+0.3,label, rotation = -45,
bbox=dict(boxstyle="rarrow,pad=0.3", alpha = 0.3))
plt.show()
输出结果:
384
也许可以使用 plt.annotate 这个功能:
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
cmap=plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
label,
xy=(x, y), xytext=(-20, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.show()