【问题标题】:Add vertical lines to separate condition-split boxplots using seaborn?使用seaborn添加垂直线以分隔条件拆分箱线图?
【发布时间】:2020-04-20 18:03:59
【问题描述】:

我正在尝试在我的 seaborn boxplot 上实现垂直线来分隔每一列,到目前为止,我似乎只能添加贯穿中间的主要线 ax.xaxis.grid(True, which='major')。这是我的代码和我想要实现的图像。谢谢!

# Custom palette
my_pal = {"Year A": "#e42628", "Year B": "#377db6"}

plt.figure(figsize=(16, 10))
sns.axes_style("whitegrid")
ax = sns.boxplot(x='variable', y="value", hue="Condition", showmeans=True, data=df, palette=my_pal, meanprops={"marker":"s","markerfacecolor":"white", "markeredgecolor":"black"})
plt.ylabel("Temperature (\xb0C)")
#ax.axvline(linewidth=2, color='r')
ax.xaxis.grid(True, which='major')

【问题讨论】:

    标签: python-3.x matplotlib seaborn


    【解决方案1】:

    您可以按如下方式定位次要 xticks 并将它们用于网格:

    from matplotlib import pyplot as plt
    from matplotlib.ticker import MultipleLocator
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    N = 200
    df = pd.DataFrame({'variable': np.repeat(list('ABCDEFGHIJ'), N // 10),
                       'value': np.random.uniform(10, 25, N),
                       'Condition': np.random.choice(['Year A', 'Year B'], N)})
    
    # Custom palette
    my_pal = {"Year A": "#e42628", "Year B": "#377db6"}
    
    plt.figure(figsize=(16, 10))
    sns.axes_style("whitegrid")
    ax = sns.boxplot(x='variable', y="value", hue="Condition", showmeans=True, data=df, palette=my_pal,
                     meanprops={"marker": "s", "markerfacecolor": "white", "markeredgecolor": "black"})
    plt.ylabel("Temperature (°C)")
    ax.xaxis.set_minor_locator(MultipleLocator(0.5))
    ax.xaxis.grid(True, which='minor', color='black', lw=2)
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      箱线图的默认宽度为 0.5(或 0.15 x [极端位置之间的距离],如果它更小的话)。

      如果你的宽度是 0.5,你可以这样做:

      import seaborn as sns, matplotlib.pyplot as plt
      
      tips = sns.load_dataset('tips')
      ax = sns.boxplot(x='day',y='total_bill',hue='sex',data=tips)
      [ax.axvline(x+.5,color='k') for x in ax.get_xticks()]
      plt.show()
      

      示例:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 2021-03-08
        • 2019-10-24
        • 2022-01-23
        相关资源
        最近更新 更多