【问题标题】:Boxplot and Data points side by side in one plot箱线图和数据点在一个图中并排
【发布时间】:2020-05-06 23:25:23
【问题描述】:
plt.figure(figsize=(8,5))
sns.boxplot(x=df.StoreType, y=df.Sales)

我得到了上面的图,但我想要并排的箱线图和数据点(不重叠,使用 seaborn 或 matplotlib),如下所示:

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    下面的代码借鉴了其他几个 SO 答案:

    1. 抵消swarmplot的思路来自:https://stackoverflow.com/a/56655927/42346
    2. 改变swarmplot的宽度的代码来自:https://stackoverflow.com/a/44542112/42346

    如果您对代码有任何疑问,请告诉我。

    import seaborn as sns, numpy as np
    import matplotlib, matplotlib.pyplot as plt
    
    tips = sns.load_dataset('tips')
    
    # adjust these as per your data 
    boxplot_width = .25 # thinner to make room for having swarmplot beside
    swarmplot_offset = -.5 # offset to left of boxplot
    xlim_offset = -1 # necessary to show leftmost swarmplot  
    
    fig = plt.figure(figsize=(6,4))
    ax = sns.swarmplot(x="day", y="total_bill", data=tips)
    
    path_collections = [child for child in ax.get_children() 
                        if isinstance(child,matplotlib.collections.PathCollection)] 
    
    for path_collection in path_collections: 
        x,y = np.array(path_collection.get_offsets()).T 
        xnew = x + swarmplot_offset
        offsets = list(zip(xnew,y)) 
        path_collection.set_offsets(offsets)
    
    sns.boxplot(x="day", y="total_bill", data=tips, width=boxplot_width, ax=ax) 
    
    def change_width(ax, new_value):
        for patch in ax.patches:
            current_width = patch.get_width()
            diff = current_width - new_value
    
            # change patch width
            patch.set_width(new_value)
    
            # re-center patch
            patch.set_x(patch.get_x() + diff * .5)
    
    change_width(ax,.25)
    
    ax.set_xticklabels(ax.get_xticklabels(), ha="right") # align labels to left
    ax.set_xlim(xlim_offset,ax.get_xlim()[1]) # to show leftmost swarmplot
    
    plt.show()
    

    示例图片:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 2023-01-23
      • 2018-04-28
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      相关资源
      最近更新 更多