python - 在 Seaborn 中,特定颜色可以覆盖已经基于另一列的色调吗?

标签 python matplotlib 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

seaborn

最佳答案

如果你想使用 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()

enter image description here

关于python - 在 Seaborn 中,特定颜色可以覆盖已经基于另一列的色调吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57379264/

相关文章:

python - 有没有办法连接 "list display"中的 2 个模型字段名称以在 Django Admin 中显示为一列?

python - 使用 Pip 安装 Python 库

python - 使用 TF-IDF 在 K 均值中绘制质心

python - 在统计注释中自定义 "star"文本格式的 p 值阈值

python - 基于值的 Seaborn 条件颜色

python - 使用 selenium webdriver_manager 在 unix 上打开 Chrome 浏览器时出错

python - 我可以使用默认字节而不是 Unicode 的 Python 3 吗?

python - 在 matplotlib 中连接两个桑基图

python - 如何确定平均线 fiddle 图边缘的 x 值

python - 迭代 Pandas 数据帧,同时跳过第一行