madman_with_a_box
madman_with_a_box

Reputation: 84

Draw matplotlib broken axis on left side only

Matplotlib's broken axis example has a break on the left and the right side of the frame and is placed exactly in the middle of the y-axis.

enter image description here

  1. How can I create an unbroken line on the right border and a broken axis on the left border?
  2. Is there a keyword argument to manually adjust the horizontal whitespace in the broken axis?
  3. Is it possible to decide where on the y-axis the break will be placed? For example, at 80% from the top border, or 20% from the top border?

Any help is greatly appreciated.

Upvotes: 1

Views: 961

Answers (1)

tomjn
tomjn

Reputation: 5389

  1. Not breaking the right axis Since the way to break the axis is to make two sets of axes, the only way I can think of the do this is to draw a line going from the top right corner of the lower axis to the bottom right corner of the upper axis. This can be done using transforms to get the relevant corners of the two axes in the axes coordinates of one of the axes
# Get the points from the lower-right corner of ax1 
# to the top-right corner of ax2 in the axes coordinates
# of ax1
low = (1, 0)
high = ax1.transAxes.inverted().transform(
    ax2.transAxes.transform((1, 1))
)

and then plotting them with transform=ax1.transAxes

ax1.plot(
    *list(zip(low, high)), "-k", 
    transform=ax1.transAxes, clip_on=False,   
    lw=ax1.spines.right.get_linewidth(),
)

2 and 3. Adjust the whitespace and position of the break This can be achieved using any way of creating different axes in matplotlib, such as passing gridspec_kw to plt.subplots e.g.

gridspec_kw = dict(height_ratios=(1, 4), hspace=0.30)
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, gridspec_kw=gridspec_kw)

As the name suggest height_ratios defines the ratios of the heights of the axes. hspace sets the vertical space between the two sets of axes (if you want to break the x-axis instead you can use wspace)

Applying these changes to the example you link, and removing the diagonal lines on the right hand side by changing

ax1.plot([0, 1], [0, 0], transform=ax1.transAxes, **kwargs)
ax2.plot([0, 1], [1, 1], transform=ax2.transAxes, **kwargs)

to

ax1.plot(0, 0, transform=ax1.transAxes, **kwargs)
ax2.plot(0, 1, transform=ax2.transAxes, **kwargs)

you get the following plot enter image description here

Upvotes: 1

Related Questions