Last active
September 1, 2023 17:26
-
-
Save camriddell/d7b01d213a19de1622a09beed1d95d19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from matplotlib.pyplot import subplots, rc, rcdefaults | |
from pandas import DataFrame | |
from numpy.random import default_rng | |
from calendar import month_name | |
# Create fake data | |
months = month_name[1:] | |
df = DataFrame({ | |
'Product A': [209, 192, 137, 108, 98, 96, 104, 120, 154, 191, 187, 215], | |
'Product B': [184, 161, 123, 96, 88, 84, 97, 109, 124, 163, 156, 175]}, | |
index=months | |
) | |
# Set up aesthetic settings for matplotlib | |
# Remove the ticks and ticklabels from the xaxis | |
# Remove ticks from the yaxis | |
# Remove all spines | |
rcdefaults() | |
rc('xtick', bottom=False, labelbottom=False) | |
rc('ytick', left=False) | |
rc('axes.spines', bottom=False, left=False, right=False, top=False) | |
# Create 2 Axes objects with barely any space between them | |
fig, (ax1, ax2) = subplots(1, 2, sharey='row', gridspec_kw={'wspace': .01}) | |
# Plot 'Product A' as horizontal bars & add labels | |
# invert the xaxis so the bars are facing to the left | |
bc = ax1.barh(df.index, df['Product A'], color='tab:blue', label='Product A') | |
ax1.bar_label(bc, label_type='center') | |
bc = ax2.barh(df.index, df['Product B'], color='tab:red', label='Product B') | |
ax2.bar_label(bc, label_type='center') | |
xmax = max([*ax1.get_xlim(), *ax2.get_xlim()]) | |
ax1.set_xlim(right=xmax) | |
ax2.set_xlim(right=xmax) | |
ax1.invert_xaxis() | |
# Add a legend to the lower center of the figure | |
# Use fig.legend since the Artists exist on different Axes | |
fig.legend(loc='lower center', frameon=False, ncols=2) | |
fig.savefig('mirrored_bar.png', bbox_inches='tight') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment