我想繪制一個 Seaborn swarmplot 的“LapTimeSeconds”與“Driver”,我希望每個群(驅動程式)在“顏色”列中以相應的顏色繪制,我還想要每個的邊緣顏色標記為給定的“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”(黃色),而化合物為“軟”時我想要邊緣顏色為 '#FF3333' (red) 。
這與我的目標相似。有沒有辦法做到這一點?

uj5u.com熱心網友回復:
要自定義 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()

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/331268.html
標籤:Python 熊猫 matplotlib 海生
