2

Is there a way to make two subplots that share their x axis scale while allowing them to have different limits.

Here is a diagram of what I'm trying to achieve: enter image description here

(the faint vertical lines are to indicate that the ticks are in the same horizontal position and will not be in the final graph)

The extra space in the bottom right will be filled with another axis. I'm guessing there is no easy way, but if there is I'd greatly appreciate it!

2 Answers 2

3

Ok, so I discovered the transforms in the matplotlib docs, and this works. Not exactly trivial, but that's ok. The graph produced here is reversed from the example: the top has the short x-axis. The concept ok though.

import matplotlib.pyplot as plt

short_ax_lim = 4.

f, (top_ax, bottom_ax) = plt.subplots(2,1,figsize=[9,5])

bottom_ax.set_xlim(0,5)
top_ax.set_xlim(0,short_ax_lim)

# first find the pixel where the bottom x-axis equals the desired limit.
short_ax_stop_pix = bottom_ax.transData.transform((short_ax_lim,0))  # (x,y) in pixels at data point (0,4)
short_ax_stop_fig = pix_to_fig.transform(short_ax_stop_pix)  # (x,y) in figure space (0,1)

top_orig_position_px = top_ax.bbox.corners()  # (ll, ul, lr, ur)
top_orig_anchor_px = top_orig_position_px[0]  # this is lower left corner.
top_orig_anchor_fig = pix_to_fig.transform(top_orig_anchor_px)  #convert to figure space
top_x_anchor, top_y_anchor = top_orig_anchor_fig

top_width = short_ax_stop_fig[0] - top_x_anchor
new_pos = (top_x_anchor, top_y_anchor,  top_width, top_ax.get_position().height)

top_ax.set_position(new_pos)
f.show()
Sign up to request clarification or add additional context in comments.

3 Comments

HI @c-wilson. Can you please point out where is the pix_to_fig function defined?
Hey @m2as3registeredservicesohmone. I think it's pix_to_fig = fig.transFigure.inverted(). I had the same question and found a hint on GitHub.
Thanks very much for this Radu. I will give it a shot
0

Using sharex will couple the axes. It's not pretty but you could use subplot2grid like this,

import matplotlib.pyplot as plt

ax1 = plt.subplot2grid((2,5), (0,0), colspan=5)
ax2 = plt.subplot2grid((2,5), (1,0), colspan=4)

ax1.set_xlim(0,5)
ax2.set_xlim(0,4)
plt.show()

1 Comment

So I just plotted this out, and it looks like it is not exact. I'm guessing that this is due to padding. At the right bound (0), it is perfect as expected, but at 4 there is an offset of a few pixels where the smaller plot is too small. Sorry but I need perfection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.