绘制散点图,其中点的颜色取决于数据类别

Plotting scatter plot where colour of point depends on category of data

我有一个数据列表 X,它是一个 Nx2 矩阵。我想根据 X 的所有第二个元素绘制每个 X 的第一个元素。 首先,我将 X 的所有第一个和第二个元素分成它们自己的列表:X_comp1X_comp2

我还有一个Nx1的类别列表(cat),它显示了X的元素属于哪个类别,即如果cat[i] = 3,则意味着X[i]属于类别3。

我想在每个类别的散点图中使用不同颜色的点。

到目前为止,我只能通过硬编码来实现这一点,但是当类别更多时,这将变得非常低效。 这是我的代码(假设有 5 个类别):

#sample of X data
X = [[-0.13085379 -0.05958517],[ 0.02593188 -0.17576942],[-0.12505032 -0.02709171],[ 0.09790905 -0.18046944],[ 0.06437596 -0.20600157],[ 0.16287853 -0.2955353 ],[-0.52093842  0.33463338],[-0.03240038 -0.05431373],[-0.09645192 -0.14241157],[ 0.0807245  -0.26893815]]

X_comp1 = []#hold all the first components of X
X_comp2 = []#hold all the second components of X

cat = [1,3,2,1,5,3,2,4,4,1] 

#for testing just use 10 values, full file has over 3000 entries and 50 categories
for i in range(10):
    X_comp1.append(X[i][0])
    X_comp2.append(X[i][1])

for x1,x2,c in zip(X_comp1,X_comp2,cat):
    if c == 1:
        plt.scatter(x1,x2,c = 'b')
    elif c == 2:
        plt.scatter(x1,x2,c = 'g')
    elif c == 3:
        plt.scatter(x1,x2,c = 'r')
    elif c == 4:
        plt.scatter(x1,x2,c = 'c')
    elif c == 5:
        plt.scatter(x1,x2,c = 'm')
plt.legend([1,2,3,4,5])
plt.show()

我想让类别的数量更加灵活,这样我就不必为每个类别编写大量的 if 语句。

为了实现这一点,我想到了一个颜色列表:

colours = ["b", "g", "r", "c", "m",...]#number of colours depends on no. of categories
#This is the only element which I would like remain hard coded, as I want to choose the colours

其中每种颜色对应一个类别。然后程序遍历所有数据并根据类别绘制每个点。但我不确定如何实施。

试试这个

color_dict = {1: 'b', 2: 'g', 3: 'r', 4: 'c', 5: 'm'}
for x1, x2, c in zip(X_comp1, X_comp2, cat):
    if c in color_dict:
        plt.scatter(x1, x2, c = color_dict[c])
plt.legend(list(color_dict.keys()))
plt.show()

我们可以删除所有 if 语句,而不是使用字典检查 c 的每个值

为了一个漂亮的情节,你也可以使用 seaborn:

import seaborn as sns
import pandas as pd
sns.set()
df = pd.DataFrame({'X_1': X_comp1,'X_2':X_comp2, 'category':cat})
sns.scatterplot(data=df,x='X_1', y='X_2', hue='category')

如果你关心哪个类别应该有什么颜色,你可以用你自己的类别颜色字典传递palette参数:

my_palette = {1: 'b', 2: 'g', 3: 'r', 4: 'c', 5: 'm'}
sns.scatterplot(data=df,x='X_1', y='X_2', hue='category', palette=my_palette)

如果您对 seaborn 的默认选择不满意,还有一堆预定义的调色板。