user308827 user308827 - 3 months ago 7
Python Question

Pandas boxplot with ranges in x-axis

I have the foll. dataframe in pandas:

value combined_delta
100 7
100 45
100 49
100 12
100 71
94.09 21
91.42 45
88.7 36
87.26 34
77.61 55
76.3 28
73.81 89
71 80
69.5 27
67.45 12
66.96 127
66.18 43
54.48 68
54.15 23
53.29 48
53.29 49
53.25 302
51.99 24
51.99 116
50.73 22
49.7 101
31.05 107
31 63
30.19 116
30.12 58
29.38 31
29.18 8
29 104
28.6 61
28.6 63
28.56 60
28.11 35
27.36 50
27.32 63
26.87 103
26.87 257
26.42 55
26.35 85
26.1 27
25.79 21
25.79 66
25.66 77
25.53 9
25.46 92
25.46 248
24.67 15
24.6 93
24.39 5
24.01 28
24.01 82
23.86 19
23.18 133
22.71 41
22.62 37
21.81 43
21.52 34
21.43 35
21.23 40
21.23 25
20 75
19.98 31
19.98 44
19.84 12
19.82 62
18.83 26
18.71 202
18.02 7
18 28
17.99 39
17.75 40
17.68 81
17.67 16
17.55 54
17.25 13
16.63 19
12.14 22
12.01 24
12 59
11.95 49
11.54 39


How can I make a boxplot where the x-axis shows ranges for
value
: 0-20, 20-40, 40-60,60-80,80-100 and the y-axis shows
combined_delta
values?

I can use seaborn like this:

ax = sns.boxplot(x="value", y="combined_delta", data=df)


However, this will not create the ranges from the x-axis the way I want

Answer
cut = pd.cut(df.value, [0, 20, 40, 60, 80, 100])

boxdf = df.groupby(cut) \
    .apply(lambda df: df.combined_delta.reset_index(drop=True)) \
    .unstack(0)

sns.boxplot(data=boxdf);

enter image description here

Comments