简体   繁体   English

为plt.scatterplot中的每个标签分配不同的颜色

[英]Assign a different colour for each label in a plt.scatterplot

I am drawing this scatterplot in python, and I would like to have the dot drawn in a different (contrasting) colour for each label. 我正在用python绘制此散点图,并且我想为每个标签用不同(对比)的颜色绘制点。 Each label has multiple points. 每个标签都有多个点。

Seems like it could be something to feed to annotate, but I am not quite sure how, as I haven't been able to find it: 似乎可能需要注解,但由于无法找到它,我不太确定该怎么做:

  for i, label in enumerate(labels):
    x, y = low_dim_embs[i, :]
    plt.scatter(x, y)
    plt.annotate(label,
                 xy=(x, y),
                 xytext=(5, 2),
                 textcoords='offset points',
                 ha='right',
                 va='bottom')

I can replace the above command by: 我可以将上述命令替换为:

plt.scatter(x, y, color=mycolors)

Which will give me manually specified colors, but for each of the entries (and there are many repetitions per entry). 这将为我手动指定颜色,但是会为每个条目(每个条目有很多重复)。 Is there any automatic way? 有没有自动的方法?

My dataset looks like this: 我的数据集如下所示:

x,y,label
1,2,label1
1,3,label1
2,-1,label1
4,1,label2
5,1,label2
...

Each coordinate belonging to labelx should have the same colour (I would probably also need those in a legend). 属于labelx的每个坐标应具有相同的颜色(我可能还需要图例中的颜色)。

The way to work around the issue of same labels to same colors is to write a script that generates a list of colors that assign a unique number to each unique value in your data (that line of code is explained in this answer ): 解决相同标签颜色相同问题的方法是编写一个脚本,该脚本生成一个颜色列表,为数据中的每个唯一值分配一个唯一编号(该行代码在此答案中进行了说明):

import numpy as np
import matplotlib.pyplot as plt

line = plt.figure()

data = [[1,1.5,3,2.4,5],[2,4.1,2.4,1,3],["apple","banana","grape","apple","banana"]]    

colors = [{ni: indi for indi, ni in enumerate(set(data[2]))}[ni] for ni in data[2]]

plt.scatter(data[0], data[1], c=colors, cmap="plasma")    

for i in range(len(data[0])):    
    plt.annotate(str(data[2][i]),
                     xy=(data[0][i], data[1][i]),
                     xytext=(data[0][i], data[1][i]),
                     textcoords='offset points',
                     ha='right',
                     va='bottom')

plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM