|
| 1 | +# Customizing violin plots |
| 2 | +# |
| 3 | +# |
| 4 | + |
| 5 | +import matplotlib.pyplot as plt |
| 6 | +import numpy as np |
| 7 | + |
| 8 | + |
| 9 | +# functions to calculate percentiles and adjacent values |
| 10 | +def percentile(vals, p): |
| 11 | + N = len(vals) |
| 12 | + n = p*(N+1) |
| 13 | + k = int(n) |
| 14 | + d = n-k |
| 15 | + if k <= 0: |
| 16 | + return vals[0] |
| 17 | + if k >= N: |
| 18 | + return vals[N-1] |
| 19 | + return vals[k-1] + d*(vals[k] - vals[k-1]) |
| 20 | + |
| 21 | + |
| 22 | +def adjacent_values(vals): |
| 23 | + q1 = percentile(vals, 0.25) |
| 24 | + q3 = percentile(vals, 0.75) |
| 25 | + uav = q3 + (q3-q1)*1.5 |
| 26 | + if uav > vals[-1]: |
| 27 | + uav = vals[-1] |
| 28 | + if uav < q3: |
| 29 | + uav = q3 |
| 30 | + lav = q1 - (q3-q1)*1.5 |
| 31 | + if lav < vals[0]: |
| 32 | + lav = vals[0] |
| 33 | + if lav > q1: |
| 34 | + lav = q1 |
| 35 | + return [lav, uav] |
| 36 | + |
| 37 | +# create test data |
| 38 | +dat = [np.random.normal(0, std, 100) for std in range(6, 10)] |
| 39 | +lab = ['a', 'b', 'c', 'd'] # labels |
| 40 | +med = [] # medians |
| 41 | +iqr = [] # inter-quantile ranges |
| 42 | +avs = [] # upper and lower adjacent values |
| 43 | +for arr in dat: |
| 44 | + sarr = sorted(arr) |
| 45 | + med.append(percentile(sarr, 0.5)) |
| 46 | + iqr.append([percentile(sarr, 0.25), percentile(sarr, 0.75)]) |
| 47 | + avs.append(adjacent_values(sarr)) |
| 48 | + |
| 49 | +# plot the violins |
| 50 | +fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(7, 5)) |
| 51 | +parts = ax.violinplot(dat, showmeans=False, showmedians=False, |
| 52 | + showextrema=False) |
| 53 | + |
| 54 | +# plot medians and averages |
| 55 | +for i in range(len(med)): |
| 56 | + ax.plot([i+1, i+1], avs[i], '-', c='black', lw=1) |
| 57 | + ax.plot([i+1, i+1], iqr[i], '-', c='black', lw=5) |
| 58 | + ax.plot(i+1, med[i], 'o', mec='none', c='white', ms=6) |
| 59 | + |
| 60 | +# customize colors |
| 61 | +for pc in parts['bodies']: |
| 62 | + pc.set_facecolor('#D43F3A') |
| 63 | + pc.set_edgecolor('black') |
| 64 | + pc.set_alpha(1) |
| 65 | + |
| 66 | +ax.get_xaxis().set_tick_params(direction='out') |
| 67 | +ax.xaxis.set_ticks_position('bottom') |
| 68 | +ax.set_xticks([x+1 for x in range(len(lab))]) |
| 69 | +ax.set_xticklabels(lab) |
| 70 | +ax.set_xlim(0.25, len(lab)+0.75) |
| 71 | +ax.set_ylabel('ylabel') |
| 72 | +ax.set_xlabel('xlabel') |
| 73 | +ax.set_title('customized violin plot') |
| 74 | + |
| 75 | +plt.subplots_adjust(bottom=0.15) |
| 76 | + |
| 77 | +plt.show() |
0 commit comments