python - 如何根据数据框的值更改边缘颜色
问题描述
我想绘制“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) 。
这与我的目标相似。有没有办法做到这一点?
解决方案
要自定义 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()
推荐阅读
- html - Outlook 电子邮件签名的简单 HTML 格式
- python - 依赖解析可视化
- python - 使用 Python 检查网站的状态变化
- python - 如何在我的网络应用程序上安全地接受和运行用户的代码?
- api - 如何将 OData $Filter 与返回 IQueryable 的端点一起使用
在 ASP.Net Core API 中? - np-complete - 每个 np-complete 问题都归结为 Halting 问题。这是真的?
- python - 如何内联显示 KivyMD 数据表
- python - numpy 分配给具有浮点数的日期的 dtype 数组导致“无法将字符串转换为浮点数:'2017-01-01T01:01:01'”错误
- c++ - c++输出格式问题
- android - Gradle 同步失败-Android studio