如何在同一张图上绘制两组箱线图?

How to plot two groups of boxplots on the same figure?

假设我在下面有一个示例数据框:


Division   Home Corners  Away Corners  

Bundesliga   5                 3
Bundesliga   5                 5
EPL          7                 4
EPL          3                 2
League 1     10                6
Serie A      3                 3
Serie A      8                 2
League 1     3                 1

我想创建一个按分区分组的每场比赛总角球的箱线图,但我希望将主场角球和客场角球分开,但在同一个数字上。与 "hue" 关键字完成的类似,但我该如何完成呢?

seaborn.boxplot

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = {'Division': ['Bundesliga', 'Bundesliga', 'EPL', 'EPL', 'League 1', 'Serie A', 'Serie A', 'League 1'],
        'Home Corners': [5, 5, 7, 3, 10, 3, 8, 3],
        'Away Corners  ': [3, 5, 4, 2, 6, 3, 2, 1]}

df = pd.DataFrame(data)

# convert the data to a long format
df.set_index('Division', inplace=True)
dfl = df.stack().reset_index().rename(columns={'level_1': 'corners', 0: 'val'})

# plot
sns.boxplot('corners', 'val', data=dfl, hue='Division')
plt.legend(title='Division', bbox_to_anchor=(1.05, 1), loc='upper left')

您可以melt原始数据并使用sns.boxplot:

sns.boxplot(data=df.melt('Division', var_name='Home/Away', value_name='Corners'),
            x='Division', y='Corners',hue='Home/Away')

输出: