Skip to content

Instantly share code, notes, and snippets.

@jeroendelfos
Created August 15, 2019 11:10
Show Gist options
  • Save jeroendelfos/539eab0b0bb712b705a249b397408cde to your computer and use it in GitHub Desktop.
Save jeroendelfos/539eab0b0bb712b705a249b397408cde to your computer and use it in GitHub Desktop.
Plot with a break in the y-axis
def bar_with_breakline(x, y, plot_type='bar', height_ratios=[10,1],
figsize=(10,5), title=None, ylabel=None, xlabel=None):
if plot_type == 'bar':
pplot = plt.bar
elif plot_type == 'line':
pplot = plt.plot
else:
sys.exit('Error: plot type not yet supported, closing')
gs = gridspec.GridSpec(2,1, height_ratios=[10,1])
fig, ax = plt.subplots(2, 1, sharex=True, figsize=figsize)
ratio = height_ratios[0]/height_ratios[1]
ax[0] = plt.subplot(gs[0])
pplot(x, y)
ax[0].set_ylim(y.min()-0.05*y.min(), y.max()+0.05*y.max())
ax[0].set_title(title)
ax[0].set_ylabel(ylabel)
# Use ticks of plot 1 for the ticks of plot 2
ytick_interval = ax[0].get_yticks()[1] - ax[0].get_yticks()[0]
ax[1] = plt.subplot(gs[1])
pplot(x, y)
ax[1].set_ylim(0, ytick_interval)
ax[1].set_xlabel(xlabel)
# hide the spines between ax and ax2
ax[0].spines['bottom'].set_visible(False)
ax[1].spines['top'].set_visible(False)
ax[0].tick_params(bottom=False, labelbottom=False) # don't put tick labels at the top
ax[1].xaxis.tick_bottom()
# Add breakline on yaxis
d = .015 # how big to make the diagonal lines in axes coordinates
# arguments to pass to plot, just so we don't keep repeating them
kwargs = dict(transform=ax[0].transAxes, color='k', clip_on=False)
ax[0].plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal
ax[0].plot((1 - d, 1 + d), (-d, +d), **kwargs) # top-right diagonal
kwargs.update(transform=ax[1].transAxes) # switch to the bottom axes
ax[1].plot((-d, +d), (1 - ratio*d, 1 + ratio*d), **kwargs) # bottom-left diagonal
ax[1].plot((1 - d, 1 + d), (1 - ratio*d, 1 + ratio*d), **kwargs) # bottom-right diagonal
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment