【问题标题】:pandas boxplots as subplots with individual y-axis熊猫箱线图作为带有单独 y 轴的子图
【发布时间】:2018-09-16 08:03:39
【问题描述】:

假设我有一个数据框,在“类型”列中包含三组“K”、“L”和“M”,例如:

df = pd.DataFrame(data={'A': random.sample(xrange(60, 100), 10),
                    'B': random.sample(xrange(20, 40), 10),
                    'C': random.sample(xrange(2000, 3010), 10),
                    'type': list(3*'K')+list(3*'L')+list(4*'M')})

对于查看单个分组箱线图,我可以使用:

for i,el in enumerate(list(df.columns.values)[:-1]):
    a = df.boxplot(el, by ='type')

我现在想将这些单个图作为子图组合在一个图中。

使用df.boxplot(by='type') 创建这样的子图。但是,由于“A”、“B”和“C”列中的可变范围,这些子图难以阅读,即信息丢失,尤其是在印刷形式中。

每个子图如何有一个单独的 y 轴?

【问题讨论】:

    标签: python pandas boxplot pandas-groupby


    【解决方案1】:

    也使用matplotlib 的可能解决方案是创建图形和子图,然后使用参数ax= 将轴传递给df.boxplot()

    例如:

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(2,2) # create figure and axes
    
    df = pd.DataFrame(data={'A': random.sample(xrange(60, 100), 10),
                        'B': random.sample(xrange(20, 40), 10),
                        'C': random.sample(xrange(2000, 3010), 10),
                        'type': list(3*'K')+list(3*'L')+list(4*'M')})
    
    for i,el in enumerate(list(df.columns.values)[:-1]):
        a = df.boxplot(el, by="type", ax=axes.flatten()[i])
    
    fig.delaxes(axes[1,1]) # remove empty subplot
    plt.tight_layout() 
    
    plt.show()
    

    【讨论】:

    • 有什么方法可以根据类型为它们着色(填充颜色\边框颜色)吗?
    猜你喜欢
    • 2015-05-04
    • 2018-11-30
    • 2023-03-10
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 2017-09-09
    • 2012-08-18
    • 1970-01-01
    相关资源
    最近更新 更多