Коробчатая диаграмма и точки данных рядом на одном графике - PullRequest
0 голосов
/ 07 мая 2020
plt.figure(figsize=(8,5))
sns.boxplot(x=df.StoreType, y=df.Sales)

enter image description here

Я получаю график выше, но я хочу, чтобы прямоугольная диаграмма и точки данных располагались рядом (без перекрытия, используя seaborn или matplotlib) как показано ниже: enter image description here

1 Ответ

3 голосов
/ 07 мая 2020

Код ниже заимствован из пары других ответов SO:

  1. Идея смещения swarmplot взята из: { ссылка }
  2. изменение ширины кода swarmplot от: { ссылка }

Если у вас есть вопросы по коду, сообщите мне.

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

...