python - 在 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",
],)
我怎样才能做到这一点?我看到这里讨论的颜色图,但不知道这是否真的符合我的需要。
解决方案
添加颜色
只需创建与每个内部列表相对应的颜色列表,然后将其提供给color
scatter 方法的参数:
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()
结果与图例:
推荐阅读
- cx-oracle - 从 Python 连接到 Oracle 时出现“ORA-28000:帐户已锁定”
- c# - 如何从 vb.net 中的 Datagridview GetXml
- python - 在 AWS 弹性搜索 {"Message":"User:anonymous is not authorized to perform:es:ESHttpGet"}
- python - 在对象内形成实例化对象的访问列表
- winforms - 如何将类Form传递给DLL中的类并继承类Form
- node.js - 使用 docker 为 restfull 节点 api 构建节点映像
- node.js - 运行nodejs程序时出错
- javascript - It seems onChange="myFunction()" is only calling my function once?
- angularjs - 垫表中行的 ElementRef
- python - 具有多个 one-hot 数组的 Keras 模型的输入形状