箱线图和数据点在一个图中并排

时间:2020-05-06 23:25:23

标签: python matplotlib seaborn

plt.figure(figsize=(8,5))
sns.boxplot(x=df.StoreType, y=df.Sales)

enter image description here

我正在获取上面的图,但是我想要像下面这样并排放置箱图和数据点(不重叠,使用seaborn或matplotlib): enter image description here

1 个答案:

答案 0 :(得分:3)

下面的代码是从其他几个答案中借来的:

  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()

示例图片:

enter image description here