Skip to content Skip to sidebar Skip to footer

Grouped Boxplot With 2 Y Axes, 2 Plotted Variables Per X Tick

I am trying to make a boxplot of an 18 year record of monthly rainfall and flood frequency. i.e. each x tick is the month, and each x tick is associated with two boxplots, one of t

Solution 1:

With some fake data and a little help from this tutorial and this answer, here a minimal example how to achieve what you want using only numpy and matplotlib:

from matplotlib import pyplot as plt
import numpy as np

rainfall = np.random.rand((12*18))*300
floods =   np.random.rand((12*18))*2

t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)

fig, ax1 = plt.subplots()

months = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
]


ax1.set_xlabel('month')
ax1.set_ylabel('rainfall', color='tab:blue')
res1 = ax1.boxplot(
    rainfall.reshape(-1,12), positions = np.arange(12)-0.25, widths=0.4,
    patch_artist=True,
)
for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
    plt.setp(res1[element], color='k')

for patch in res1['boxes']:
    patch.set_facecolor('tab:blue')



ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
ax2.set_ylabel('floods', color='tab:orange')
res2 = ax2.boxplot(
    floods.reshape(-1,12), positions = np.arange(12)+0.25, widths=0.4,
    patch_artist=True,
)
##from https://stackoverflow.com/a/41997865/2454357for element in ['boxes', 'whiskers', 'fliers', 'means', 'medians', 'caps']:
    plt.setp(res2[element], color='k')

for patch in res2['boxes']:
    patch.set_facecolor('tab:orange')

ax1.set_xlim([-0.55, 11.55])
ax1.set_xticks(np.arange(12))
ax1.set_xticklabels(months)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

The result looks something like this:

result of above code

I think with a little fine tuning this can actually look quite nice.

Post a Comment for "Grouped Boxplot With 2 Y Axes, 2 Plotted Variables Per X Tick"