如何根据数据框的值更改边缘颜色

How to change edgecolor according to value of a dataframe

我想绘制 'LapTimeSeconds' 与 'Driver' 的 Seaborn swarmplot,我希望每个群(驱动程序)都以 'Colour' 列中相应的颜色绘制,我还希望每个标记的边缘颜色是给定的 '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',例如化合物是 'medium' 我希望边缘颜色是“#ffd300”(黄色)并且其中化合物是 'soft' 我希望边缘颜色是“#FF3333”(红色)。

这与我的目标相似。有办法吗?

要自定义 swarmplot 中的每个标记,请设置指定的颜色,因为它可以从集合中获得。此外,要更改每个箱线图的颜色,请更改线条对象的颜色,因为它包含在 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()