首页 > 解决方案 > 在 np.array 中使用颜色

问题描述

我有以下带有 numpy 的 x,y 散点

a = np.array([
[5.033,-3.066],
[5.454,-3.492],
[-1.971,0.384],
],)
x, y = a.T
plt.scatter(x, y)
plt.ylabel('Yv')
plt.show()

我想用颜色画点。我的意思是,像这样:

a = np.array([
[5.033,-3.066] and color="black",
[5.454,-3.492] and color="black",
[-1.971,0.384] and color="red",
],)

我怎样才能做到这一点?我看到这里讨论的颜色图,但不知道这是否真的符合我的需要。

标签: pythonnumpy

解决方案


添加颜色

只需创建与每个内部列表相对应的颜色列表,然后将其提供给colorscatter 方法的参数:

colors = ["black", "black", "red"]
plt.scatter(x, y, color=colors)

结果 :

带有彩色标记的散点图

您可以使用字符串来指定您想要的颜色。可用的颜色字符串都是 HTML 颜色名称(大写或小写)。在这里检查它们:HTML颜色

您还可以像这样给出十六进制 RGB 值(例如粉红色):

'#FFB6C1'

...或者作为一个 RGB 值的元组或列表,范围从 0 到 1,像这样(仍然是粉红色):

[1.0, 0.75, 0.8]

资料来源:Matplotlib 颜色文档

添加图例:

最简单的方法是按行迭代地散布:

a = np.array([
[5.033,-3.066],
[5.454,-3.492],
[-1.971,0.384],
],)
x, y = a.T

# Creating colors and class names beforehand.
colors = ["black", "black", "red"]
classes = ["class1", "class2","class3"]
# Calling scatter per row, to differentiate each class
for x_per_class, y_per_class, color, label in zip(x, y, colors, classes):
    plt.scatter(x=x_per_class, y=y_per_class, color=color, label=label)

# Adding legends
plt.legend()

plt.ylabel('Yv')
plt.show()

结果与图例:

带有图例的颜色散点图


推荐阅读