gpt4 book ai didi

python - 使用 seaborn 的分组箱线图

转载 作者:行者123 更新时间:2023-11-28 22:34:00 24 4
gpt4 key购买 nike

我在 python panda DataFrame 中有以下数据。我想分组箱形图类似于 https://stanford.edu/~mwaskom/software/seaborn/examples/grouped_boxplot.html 中的箱形图

对于每个 id,我想并排绘制两个箱线图。我如何实现这一点。我尝试用 seaborn 包绘制它但没有成功。

id               predicted                              real
1 [10, 10, 10] [16, 18, 20]
2 [12, 12, 15] [15, 17, 19, 21, 23]
3 [20, 5, 4, 4] [29, 32]
4 [25, 25, 25, 24, 21] [21, 24, 25, 26, 28, 29, 30, 33]
5 [20, 20, 20, 21] [21, 22, 24, 26, 28, 30, 31, 32]
6 [8, 3, 3, 14] [25, 27]
7 [1, 4, 4, 4, 5, 6, 10] [69, 71, 72]
8 [11, 11, 11, 11] [19, 21, 22, 23, 24]
9 [7, 6, 9, 9] [19, 26, 27, 28]
10 [30, 30, 30, 30, 30] [38, 39]

最佳答案

请注意您正在查看的示例中的表结构

import seaborn as sns

tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", hue="sex", data=tips, palette="PRGn")
sns.despine(offset=10, trim=True)

enter image description here

tips.head()

enter image description here


我们的目标是像这样布置您的餐 table

设置

from StringIO import StringIO
import pandas as pd

text = """id predicted real
1 [10, 10, 10] [16, 18, 20]
2 [12, 12, 15] [15, 17, 19, 21, 23]
3 [20, 5, 4, 4] [29, 32]
4 [25, 25, 25, 24, 21] [21, 24, 25, 26, 28, 29, 30, 33]
5 [20, 20, 20, 21] [21, 22, 24, 26, 28, 30, 31, 32]
6 [8, 3, 3, 14] [25, 27]
7 [1, 4, 4, 4, 5, 6, 10] [69, 71, 72]
8 [11, 11, 11, 11] [19, 21, 22, 23, 24]
9 [7, 6, 9, 9] [19, 26, 27, 28]
10 [30, 30, 30, 30, 30] [38, 39]"""

df = pd.read_csv(StringIO(text), sep='\s{2,}', engine='python', index_col=0)

df = df.stack().str.strip('[]') \
.str.split(', ').unstack()
df

enter image description here


以正确的格式获取表格

df1 = df.stack().apply(pd.Series).stack().astype(int) \
.rename_axis(['id', 'reality', None]) \
.rename('value').reset_index(['id', 'reality']) \
.reset_index(drop=True)

df1.head()

enter image description here

sns.boxplot(x='id', y='value', hue='reality', data=df1, palette='PRGn')
sns.despine(offset=10, trim=True)

enter image description here

关于python - 使用 seaborn 的分组箱线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39344167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com