我有3个数组,如下所示:
x = [1,2,3,4,5]
y = [5,4,3,2,1]
c = [0,0,1,0,1]
plt.figure(figsize = (12,9))
plt.scatter(x = x, y = y, c = c)
plt.legend(['0', '1'])
但是我想要的是将颜色区分为0和1。
解决方案here对类进行for循环以获得所需的结果。
我也尝试过对plt.scatter()
对象进行迭代,但这是不可迭代的。
那里有某种简单的解决方案吗?最好没有循环,只有大约1行代码?
答案 0 :(得分:0)
还没有。但是Matplotlib很快就会发布一个简单的scatter + legend分散版本,不需要多次调用。
请注意,您还可以使用the Seaborn scatterplot function生成散点图,其中的标签在一行中(请参见Seaborn文档中的以下内容):
sns.scatterplot(data=tips, x="total_bill", y="tip", hue="time")
答案 1 :(得分:0)
您可以使用适当的标签一张一张地循环绘制所有不同的数据集。 在这里,我先绘制红色的点,然后绘制绿色的点。
import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [5,4,3,2,1]
c = [0,0,1,0,1]
unique = list(set(c))
colors = ['red','green']
for i, u in enumerate(unique):
xi = [x[j] for j in range(len(x)) if c[j] == u]
yi = [y[j] for j in range(len(x)) if c[j] == u]
plt.scatter(xi, yi, c=colors[i], label=str(u))
plt.legend()
plt.show()