Skip to content

Instantly share code, notes, and snippets.

@camriddell
Last active September 1, 2023 17:27
Show Gist options
  • Save camriddell/0b48196e159f6eb9e6effffbca3b633c to your computer and use it in GitHub Desktop.
Save camriddell/0b48196e159f6eb9e6effffbca3b633c to your computer and use it in GitHub Desktop.
Example of how one can use matplotlib transforms to inset an axes along each bar of a bar chart.
from matplotlib.pyplot import subplots, show, rcParams
from numpy.random import default_rng
from pandas import DataFrame
rcParams['font.size'] = 16
for side in ['left', 'right', 'top', 'bottom']:
rcParams[f'axes.spines.{side}'] = False
rng = default_rng(0)
df = DataFrame({
'$\mu=40,\sigma=3$': rng.normal(40, 3, size=300),
'$\mu=65,\sigma=5$': rng.normal(65, 5, size=300),
'$\mu=50,\sigma=8$': rng.normal(50, 10, size=300),
})
agg_df = df.mean()
fig, ax = subplots(figsize=(8,8))
bars = ax.bar(agg_df.index, df.mean())
for rect, label in zip(bars, df.columns):
x_data_pos = rect.get_x()
hist_ax = ax.inset_axes(
(x_data_pos, 0, rect.get_width(), 1),
transform=ax.get_xaxis_transform(),
sharey=ax
)
hist_ax.hist(
df[label], orientation='horizontal',
ec='gray', fc='white',
alpha=.3, rwidth=.7
)
hist_ax.patch.set_alpha(0)
hist_ax.xaxis.set_visible(False)
hist_ax.yaxis.set_visible(False)
ax.patch.set_color('#f4f4f4')
ax.yaxis.grid(color='lightgray')
ax.yaxis.set_tick_params(width=0)
ax.set_axisbelow(True)
ax.set_title('Insetting a histogram on each bar\nof a bar chart')
show()
fig.savefig('inset_axes_example.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment