Matplotlib 中散点图的不同标签

时间:2021-07-30 12:53:47

标签: python matplotlib plot

我有以下数据和代码,我试图用散点图绘制数据,但是我不知道如何在实际绘制中分离类的标签:

X = np.array([[3,4],[1,4],[2,3],[6,-1],[7,-1],[5,-3],[2,4]] )
y = np.array([-1,-1, -1, 1, 1 , 1, 1 ])

[...]
plt.axline((0,b),slope=a, color='r', linestyle='-', label="Decision Boundy")
plt.scatter(X[:,0],X[:,1],c=y)
plt.legend()
plt.show()

导致情节:

enter image description here

是否可以为颜色/类别设置单独的标签,或者我是否必须单独绘制它们?

1 个答案:

答案 0 :(得分:0)

给你:

import numpy as np
import matplotlib.pyplot as plt

X = np.array([[3,4],[1,4],[2,3],[6,-1],[7,-1],[5,-3],[2,4]] )
y = np.array([-1,-1, -1, 1, 1 , 1, 1 ])

# get indices of each label
class_a = np.where(y == 1)
class_b = np.where(y == -1)

fig, ax = plt.subplots()
b = 1.5
a = 1
ax.axline((0,b),slope=a, color='r', linestyle='-', label="Decision Boundy")
ax.scatter(X[class_a][:,0],X[class_a][:,1],c='y', label="class a")
ax.scatter(X[class_b][:,0],X[class_b][:,1],c='b', label="class b")
ax.legend()
ax.set_xlim(-10,10)
ax.set_ylim(-10,10)
plt.show()

enter image description here

相关问题