首页 > 解决方案 > 在 Seaborn 中,特定颜色可以覆盖已经基于另一列的色调吗?

问题描述

我试图在 seaborn 中绘制,以便色调基于一列定义我的数据点,如果另一列值为 1,则应该覆盖色调。

我正在为 K 中的异常检测进行此操作,因此我为不同的集群绘制色调,这很好,但现在在同一个图中,如果该行的“异常”列 = 1,那么我想显示该数据点红色的。这可能吗?

df = pd.DataFrame({'var1': [1, 2, 3, 4, 5, 6, 7], 
                    'var2': [100, 200, 300, 400, 500, 600, 700], 
                    'cluster': [0,0,0,0,0,1,1], 'anomalies':[1,1,1,0,0,0,0]})
sns.scatterplot(x='var1', y='var2', hue='cluster', data=df)

例如。在上面的代码中,不知何故我应该能够根据 label1 值传递自定义颜色 预期:我应该能够根据一列绘制色调,并根据另一列绘制自定义颜色

编辑:由于@ImportanceOfBeingErnest 询问了使用 seaborn 而不是 matplotlib 的原因,我想使用 seaborn 而不是 matplotlib,因为绘图更干净。例如。 matplotlib

海运

标签: pythonmatplotlibseaborn

解决方案


如果你想使用 matplotlib,它可能看起来像这样。为异常创建一个散点图,为其余的创建一个散点图。

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df = pd.DataFrame({'var1': [1, 2, 3, 4, 5, 6, 7], 
                    'var2': [100, 200, 300, 400, 500, 600, 700], 
                    'cluster': [0,0,0,0,0,1,1], 'anomalies':[1,1,1,0,0,0,0]})

plt.style.use("seaborn-whitegrid")
cmap = sns.cubehelix_palette(256, as_cmap=True)

sc1 = plt.scatter(x='var1', y='var2', c='cluster', data=df[df['anomalies'] == 0], cmap=cmap)
sc2 = plt.scatter(x='var1', y='var2', color="red", data=df[df['anomalies'] == 1])  

h, l = sc1.legend_elements()
plt.legend(h+[sc2], l+["anomalies"])
plt.show()

在此处输入图像描述


推荐阅读