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