[英]How to assign color to scatter point
I'm trying to assign a color to points in a matplotlib scatter plot based on a value that is not related to the x or y value. 我正在尝试根据与x或y值无关的值为matplotlib散点图中的点分配颜色。 Each point can be, for example, one of 3 values, so I want three different colors for the 3 possible values.
例如,每个点可以是3个值之一,因此我想为3个可能的值使用三种不同的颜色。 So, there are 3 arrays: x_arr, y_arr and val_arr where each element of val_arr can be 1, 2 or 3. Seems like most of the examples I've seen have the color based on the position in the array, and not based on an independent value.
因此,共有3个数组:x_arr,y_arr和val_arr,其中val_arr的每个元素可以为1、2或3。似乎像我看到的大多数示例一样,其颜色取决于数组中的位置,而不是基于一个独立的价值。
In order to get a high contrast between the 3 kinds of points for better visibility where there are many points, I've done something like this: 为了在三种点之间获得较高的对比度,以便在有许多点的情况下更好地查看,我做了如下操作:
pt_color = plt.cm.Dark2(np.linspace(0, 1, 3))
What I cannot figure out is how to assign the right color for each value element. 我无法弄清楚如何为每个值元素分配正确的颜色。 Conceptually, I would like to do something like this,
从概念上讲,我想做这样的事情,
gr.scatter(x_arr, y_arr, c=val_arr, cmap=pt_color)
where each element of val_arr is mapped to a color using pt_color, but the above does not work (I get a TypeError because pt_color is unhashable type). 其中val_arr的每个元素都使用pt_color映射到一种颜色,但是以上方法不起作用(由于pt_color是不可散列的类型,因此出现TypeError)。
Any pointers are appreciated. 任何指针表示赞赏。
import matplotlib.pyplot as plt
from numpy.random import random, randint
X = random(10)
Y = random(10)
val_arr = randint(low=0, high=3, size=10)
plt.scatter(X, Y, c=val_arr,
s=40)
plt.colorbar()
plt.show()
spaces the val_arr values out over the default colormap, and the colorbar explains what the val_arr colors mean. 将val_arr值间隔在默认颜色表上,并且颜色栏说明val_arr颜色的含义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.