首页 > 解决方案 > 如何根据数据框的值更改边缘颜色

问题描述

我想绘制“LapTimeSeconds”与“Driver”的Seaborn swarmplot,我希望每个swarm(驱动程序)都以“颜色”列中的相应颜色绘制,我还希望每个swarm(驱动程序)的边缘颜色标记为给定的“Compound_colour”

我有一个数据框 df,看起来像:

Driver   Colour  LapNumber   LapTimeSeconds   Compound   Compound_colour
HAM    #00d2be       2          91.647      MEDIUM         #ffd300
HAM    #00d2be       5          91.261      MEDIUM         #ffd300
HAM    #00d2be       8          91.082        SOFT         #FF3333
VER    #0600ef       3          91.842      MEDIUM         #ffd300
VER    #0600ef       6          91.906      MEDIUM         #ffd300
NOR    #ff8700       10         90.942        SOFT         #FF3333

这是我目前拥有的一些代码。

sns.set_palette(df['Colour'].unique().tolist())

ax = sns.boxplot(x="Driver", y="LapTimeSeconds", data=df, width = 0.8, color = 'white')

ax = sns.swarmplot(x="Driver", y="LapTimeSeconds", data=df,  size = 9, linewidth=1)

这给出了一个看起来像这样的情节

阴谋

但是,我希望每个标记的边缘颜色为相应的“Compound_colour”,例如化合物为“中等”我希望边缘颜色为“#ffd300”(黄色)并且化合物为“柔和”我想要edgecolor 为 '#FF3333' (red) 。

这与我的目标相似。有没有办法做到这一点?

在此处输入图像描述

标签: pythonpandasmatplotlibseaborn

解决方案


要自定义 swarmplot 中的每个标记,请设置指定的颜色,因为它可以从集合中获得。此外,要更改每个箱线图的颜色,请更改 line 对象的颜色,因为它包含在 ax.artists 中。

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import colors

sns.set_palette(df['Colour'].unique().tolist())
fig,ax = plt.subplots()

ax =sns.boxplot(x="Driver", y="LapTimeSeconds", data=df, width=0.8, color='white')
swarm = sns.swarmplot(x="Driver", y="LapTimeSeconds", data=df, size=9, linewidth=1)

swarm.collections[0].set_ec(colors.to_rgba('#ffd300', 1.0))
swarm.collections[1].set_ec(colors.to_rgba('#FF3333', 1.0))
swarm.collections[2].set_ec(colors.to_rgba('#FF3333', 1.0))
swarm.collections[0].set_edgecolors(['#FF3333','#ffd300','#ffd300'])

colors = ['#00d2be','#0600ef','#ff8700']

for i, artist in enumerate(ax.artists):
    # print(i, artist)
    artist.set_edgecolor(colors[i])
    for j in range(i*6,i*6+6):
        line = ax.lines[j]
        line.set_color(colors[i])
        line.set_mfc(colors[i])
        line.set_mec(colors[i])

plt.show()

在此处输入图像描述


推荐阅读