【问题标题】:How can I adjust the size of the whiskers in a Seaborn boxplot?如何调整 Seaborn 箱线图中胡须的大小?
【发布时间】:2019-09-14 23:42:44
【问题描述】:

我想在下面的箱线图中加宽胡须线。

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

data = pd.DataFrame({'Data': np.random.random(100), 'Type':['Category']*100})

fig, ax = plt.subplots()

# Plot boxplot setting the whiskers to the 5th and 95th percentiles
sns.boxplot(x='Type', y='Data', data=data, color = 'gray', whis = [5,95])

# Adjust boxplot and whisker line properties
for p, artist in enumerate(ax.artists):
    artist.set_edgecolor('blue')
    for q in range(p*6, p*6+6):
        line = ax.lines[q]
        line.set_color('pink')

我知道如何调整胡须颜色和线宽,但我无法弄清楚如何增加胡须的长度。我最接近的是尝试使用line.set_xdata([q/60-0.5, q/60+0.5]),但我得到了错误

ValueError: shape mismatch: objects cannot be broadcast to a single shape    

理想情况下,我希望胡须百分位线与框的宽度相同。我该怎么做?

【问题讨论】:

    标签: python-3.x matplotlib seaborn boxplot


    【解决方案1】:

    正如您所注意到的,每个框都绘制了 6 条线(因此您的 p*6 索引)。

    索引为p*6+4 的线具有框的宽度(即框内的中线)。所以我们可以用它来设置其他线条的宽度。

    您要更改的行具有索引p*6+2p*6+3

    import pandas as pd
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    data = pd.DataFrame({'Data': np.random.random(100), 'Type':['Category']*100})
    
    fig, ax = plt.subplots()
    
    # Plot boxplot setting the whiskers to the 5th and 95th percentiles
    sns.boxplot(x='Type', y='Data', data=data, color = 'gray', whis = [5,95])
    
    # Adjust boxplot and whisker line properties
    for p, artist in enumerate(ax.artists):
        artist.set_edgecolor('blue')
        for q in range(p*6, p*6+6):
            line = ax.lines[q]
            line.set_color('pink')
    
        ax.lines[p*6+2].set_xdata(ax.lines[p*6+4].get_xdata())
        ax.lines[p*6+3].set_xdata(ax.lines[p*6+4].get_xdata())
    

    这也适用于具有多个框的示例:

    import pandas as pd
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.set(style="whitegrid")
    tips = sns.load_dataset("tips")
    ax = sns.boxplot(x="day", y="total_bill", data=tips)
    
    # Adjust boxplot and whisker line properties
    for p, artist in enumerate(ax.artists):
        artist.set_edgecolor('blue')
        for q in range(p*6, p*6+6):
            line = ax.lines[q]
            line.set_color('pink')
    
        ax.lines[p*6+2].set_xdata(ax.lines[p*6+4].get_xdata())
        ax.lines[p*6+3].set_xdata(ax.lines[p*6+4].get_xdata())
    

    【讨论】:

    • 太棒了!感谢您的解释,我试图调整错误的行。
    • 不客气。为了将来参考,如果您在 q 循环中打印出 line.get_xdata(),您可以快速查看哪些行具有哪些 x 值,这就是我如何计算出哪一个是哪个 :)
    猜你喜欢
    • 2015-01-11
    • 2018-01-19
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 2018-02-23
    • 2016-01-25
    相关资源
    最近更新 更多