Seaborn boxplot with 2 y-axes

后端 未结 1 1284
情书的邮戳
情书的邮戳 2021-01-20 16:20

How can I create a seaborn boxplot with 2 y-axes? I need this because of different scales. My current code will overwrite the first box in the boxplot, eg. it is populated b

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-20 17:09

    It may not make too much sense to use seaborn here. Using usual matplotlib boxplots allows you to use the positions argument as expected.

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    plt.style.use('ggplot')
    
    df = pd.DataFrame({'A': pd.Series(np.random.uniform(0,1,size=10)),
                       'B': pd.Series(np.random.uniform(10,20,size=10)),
                       'C': pd.Series(np.random.uniform(10,20,size=10))})
    
    fig, ax1  = plt.subplots(figsize=(7.8, 5.51))
    
    props = dict(widths=0.7,patch_artist=True, medianprops=dict(color="gold"))
    box1=ax1.boxplot(df['A'].values, positions=[0], **props)
    
    ax2 = ax1.twinx()
    box2=ax2.boxplot(df[['B','C']].values,positions=[1,2], **props)
    
    ax1.set_xlim(-0.5,2.5)
    ax1.set_xticks(range(len(df.columns)))
    ax1.set_xticklabels(df.columns)
    
    for b in box1["boxes"]+box2["boxes"]:
        b.set_facecolor(next(ax1._get_lines.prop_cycler)["color"])
    plt.show()
    

    0 讨论(0)
提交回复
热议问题