如何迭代 linecolor 以获得最新更新的 seaborn boxplot 以匹配我的调色板

问题描述 投票:0回答:2

在最新的seaborn更新(v 0.13.0)中为箱线图添加了一个新参数linecolor。 sns.箱线图。

https://seaborn.pydata.org/ generated/seaborn.boxplot.html

目前,只能为 sns.boxplot 的 linecolor 参数传递“颜色”。

我想知道是否有办法匹配我的调色板,我将其作为 linecolor 参数的字典传递。

这是我的箱线图现在的样子(出于 IP 目的,我编辑了一些信息):

这是我要传递的命令:

palette = {'Day1': '#B4C7E7', 'Day2': 'dodgerblue', 'Day3': '#2F5597'}

这是我想要的箱线图的样子:

忽略图例大小和yticks的差异,这些参数是我自己更改的并且很容易制作。正如您在该图中看到的,线条颜色与调色板相匹配,我使用另一个图像软件完成了此操作,但这显然是一个麻烦且乏味的练习。显然我想自动化这个过程。

我认为我不需要提供更多信息来提供我正在使用的数据框或我如何实例化对这个问题的 sns.boxplot 的调用,这真的很简单。

见上文。我提供的一切对于SO观众来说应该足够了。

pandas parameters seaborn boxplot palette
2个回答
0
投票

sns.boxplot
linecolor
仅支持单一颜色,与色调无关。好像也不支持
linecolor='face'

如果您使用的是最新的 matplotlib 和 seaborn 版本,您可以循环生成的箱线图并更新线条颜色。

以下代码已使用 matplotlib 3.8.2 和 seaborn 0.13.1 进行了测试:

import matplotlib.pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")

ax = sns.boxplot(data=tips, x="smoker", y="tip", hue="day",
                 hue_order=['Fri', 'Sat', 'Sun'],
                 palette={'Fri': '#B4C7E7', 'Sat': 'dodgerblue', 'Sun': '#2F5597'})
for boxplot in ax.containers:
    color = boxplot.boxes[0].get_facecolor()
    plt.setp(boxplot.boxes, edgecolor=color)
    plt.setp(boxplot.caps, color=color)
    plt.setp(boxplot.fliers, color=color, markeredgecolor=color)
    plt.setp(boxplot.means, color=color)
    plt.setp(boxplot.medians, color=color)
    plt.setp(boxplot.whiskers, color=color)
for handle in ax.legend_.legend_handles: # update the legend
    handle.set_edgecolor(handle.get_facecolor())
plt.tight_layout()
plt.show()


0
投票

这有点挑剔,但在 v0.13+ 中,您可以将未填充的箱线图分层到填充的箱线图上:

tips = sns.load_dataset("tips")
spec = dict(data=tips, x="day", y="total_bill", hue="sex", gap=.1)
sns.boxplot(**spec, linewidth=0, showfliers=False, boxprops=dict(alpha=.5))
sns.boxplot(**spec, fill=False, legend=False)

© www.soinside.com 2019 - 2024. All rights reserved.