Indicate y-Axis does not start at 0 in matplotlib without multiple subgraphs

Viewed 128

I am aware of the broken axis example from matplotlib but am wondering if there is a purely optical solution to this problem if you do not want to actually plot two different areas of the scale but just optically indicate that the graph is not starting at 0.

How to just add to // to the axis as is? Ugly solutions welcome (i.e. having the axis go through as in ---/-/--- instead of ---/ /---)

1 Answers

One way to do what you want from the broken axis code example you provided in your question is to use the second axis ax2 as a placeholder axis with an height_ratio of 0. The only thing you would be plotting onto this axis is the bottom horizontal line that shows that the axis is not starting at 0. Due to the height ratio of your ax2 being equal to 0, only horizontal lines can be plotted onto the ax2 axis which means that you should also modify the diagonal plotted on your ax axis to horizontal lines:

See code below for more details:

import matplotlib.pyplot as plt
import numpy as np

pts = np.array([
    0.015, 0.166, 0.133, 0.159, 0.041, 0.024, 0.195, 0.039, 0.161, 0.018,
    0.143, 0.056, 0.125, 0.096, 0.094, 0.051, 0.043, 0.021, 0.138, 0.075,
    0.109, 0.195, 0.050, 0.074, 0.079, 0.155, 0.020, 0.010, 0.061, 0.008])

pts[[3, 14]] += .8

f, (ax, ax2) = plt.subplots(2, 1, sharex=True,gridspec_kw={'height_ratios': [1, 0]})


ax.plot(pts)
ax.set_ylim(.78, 1.)  # outliers only

ax.spines['bottom'].set_visible(False)
ax2.spines['top'].set_visible(False)

ax.xaxis.tick_top()
ax.tick_params(labeltop=False)  # don't put tick labels at the top
ax2.xaxis.tick_bottom()

d = .015  
kwargs = dict(transform=ax.transAxes, color='k', clip_on=False)
ax.plot((-d, +d), (-d, -d), **kwargs)       
ax.plot((1 - d, 1 + d), (-d, -d), **kwargs)  

kwargs.update(transform=ax2.transAxes)
ax2.plot((-d, +d), (1 + d, 1 + d), **kwargs) 
ax2.plot((1 - d, 1 + d), (1 + d, 1 + d), **kwargs)  
ax2.set_yticks([])

plt.show()

And the output gives:

enter image description here

Related