【问题标题】:How to plot two groups of boxplots on the same figure?如何在同一个图形上绘制两组箱线图?
【发布时间】:2020-09-15 01:27:29
【问题描述】:

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


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”关键字的作用,但我该如何实现呢?

【问题讨论】:

    标签: python-3.x matplotlib seaborn boxplot


    【解决方案1】:

    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')
    

    【讨论】:

      【解决方案2】:

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

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

      输出:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-12
        • 2014-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多