import matplotlib.pyplot as plt
import numpy as np
import random
#build dataset as dictionary
data = {}
data['dataset1'] = {}
data['dataset2'] = {}
data['dataset3'] = {}
#simulate data
n = 100
for k,v in data.items():
upper = random.randint(0, 1000)
v['sample A'] = np.random.uniform(0, upper, size=n)
v['sample B'] = np.random.uniform(0, upper, size=n)
v['sample C'] = np.random.uniform(0, upper, size=n)
fig, axes = plt.subplots(ncols=3, sharey=True)
fig.subplots_adjust(wspace=0)
#build subplots
colors = ['pink', 'lightblue', 'lightgreen']
for ax, name in zip(axes, ['dataset1', 'dataset2', 'dataset3']):
bplot = ax.boxplot([data[name][item] for item in ['sample A', 'sample B', 'sample C']], patch_artist=True)
for patch, color in zip(bplot['boxes'], colors):
patch.set_facecolor(color)
ax.set(xticklabels=['sample A', 'sample B', 'sample C'])
ax.margins(0.05)
#plot labels
for ax in fig.axes:
plt.sca(ax)
plt.xticks(ha = 'right', rotation=45)
# place legend
plt.legend([bplot["boxes"][0], bplot["boxes"][1], bplot["boxes"][2]],
['A', 'B', 'C'],
bbox_to_anchor=(1, 1))
plt.show()