python - 如何分别为每个点指定颜色来创建散点图?

标签 python matplotlib colors

我使用 matplotlib 创建了一个散点图动画,它每秒显示一个新点,并以部分透明的方式显示所有旧点。每个点都由 xy 定义,但也由类别 s 定义。我希望点的颜色与其类别相关联。理想情况下,这意味着数组 s 包含值 1、2 和 3,并且属于这些值的颜色是单独定义的。但是,我无法让它工作。

我要做的是在 s 中单独指定每个点的边缘颜色,代码如下所示。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as plti
import matplotlib.animation

s = [[1,0,0],[0,1,0],[0,0,1]];
x = [525,480,260];
y = [215,180,180];

img = plti.imread('myimage.png')
fig, ax = plt.subplots()
plt.imshow(img)
plt.axis('off')

x_vals = []
y_vals = []
intensity = []
iterations = len(x)
colors = []

t_vals = np.linspace(0,iterations-1,iterations,dtype=int)
scatter = ax.scatter(x_vals, y_vals, s=100, c=colors, vmin=0, vmax=1)

def init():
    pass

def update(t):
    global x, y, x_vals, y_vals, intensity
    x_vals.extend([x[t]])
    y_vals.extend([y[t]])
    scatter.set_offsets(np.c_[x_vals,y_vals])
    intensity = np.concatenate((np.array(intensity), np.ones(1)))
    if len(intensity) > 1:
        intensity[-2] = 0.5
    scatter.set_array(intensity)
    colors.extend([s[t]])
    scatter.set_color(colors)

    return ani

ani = matplotlib.animation.FuncAnimation(fig, update, frames=t_vals, interval=1000, repeat=False, init_func=init)
plt.show()

简单地将 c=colors 更改为 facecolor=colors 是行不通的。我也尝试过使用颜色图,但我也无法使用它。

上面代码生成的动画如下所示。

enter image description here

但是,动画应该是这样的..

enter image description here

所以我的问题是;有人知道如何将每个点的面部颜色与该点所属的类别联系起来吗?

最佳答案

在 matplotlib 中用不同颜色的点绘制图的正常方法是将颜色列表作为参数传递。

例如:

import matplotlib.pyplot
matplotlib.pyplot.scatter([1,2,3],[4,5,6],color=['red','green','blue'])

enter image description here

但是如果出于某种原因你只想通过一个调用来完成它,你可以制作一个大的颜色列表,加上列表理解和一些地板划分:

import matplotlib
import numpy as np

X = [1,2,3,4]
Ys = np.array([[4,8,12,16],
      [1,4,9,16],
      [17, 10, 13, 18],
      [9, 10, 18, 11],
      [4, 15, 17, 6],
      [7, 10, 8, 7],
      [9, 0, 10, 11],
      [14, 1, 15, 5],
      [8, 15, 9, 14],
       [20, 7, 1, 5]])
nCols = len(X)  
nRows = Ys.shape[0]

colors = matplotlib.cm.rainbow(np.linspace(0, 1, len(Ys)))

cs = [colors[i//len(X)] for i in range(len(Ys)*len(X))] #could be done with numpy's repmat
Xs=X*nRows #use list multiplication for repetition
matplotlib.pyplot.scatter(Xs,Ys.flatten(),color=cs)

enter image description here

关于python - 如何分别为每个点指定颜色来创建散点图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57377371/

相关文章:

python - 使用 Python 多处理加速从 Postgres 获取大表到 CSV

python - 仅当列值是字符串时才将它们转换为小写

python - 获取matplotlib中矩形选择的数据

emacs - 如何在 Emacs 中更改 [] 和 () 的颜色主题?

r - 在 R 中设置自定义色标

python - 将命名元组的值从字符串转换为整数

python - 更改范围函数内的步长值?

python - 导入 matplotlib 和 matplotlib.pyplot 有什么区别?

python - 内存不足 : np. meshgrid

r - 链接颜色与整数ggplot2