填充箱线图后面的 y 轴

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

我有这个箱线图:

boxplot

我需要用像这样的颜色填充图层:

boxplot and layers

最后一个是在 R 中创建的,但我尝试使用 Matplotlib 使用 Python 创建它。我还没有在互联网上看到任何有关如何执行此操作的示例。

我尝试过

plt.fill_between
,但没有成功,或者至少我不知道如何正确适应它。

python matplotlib boxplot
1个回答
0
投票

您可以使用位置/颜色列表和带有

axhspan
:

的循环
import numpy as np
import pandas as pd
import seaborn as sns

a = np.arange(100)
df = pd.DataFrame({'var': a//25, 'value': a})

ax = sns.boxplot(data=df, x='var', y='value')

colors = ['#AC5079', '#EC5662', '#FDF7AD', '#71C18C', '#8ECEEA']
bins = [20, 40, 50, 60, 100]

xmin, ymin = ax.get_xlim()

base = 0
for top, c in zip(bins, colors):
    ax.axhspan(base, top, color=c, zorder=0)
    base = top

输出:

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