droid192
droid192

Reputation: 2232

Align second y axis with the one on the left?

I introduced a twin yaxis to plot the cumulative but the 0 does not start at the bottom of the image or is at least at the same height of the left yaxis.

How to align the 0 point of the right to the y on the left?

fig, ax = plt.subplots(1,1, figsize=(15,1.5*2.5))
ax.hist(np.arange(100), np.arange(100))
axt = ax.twinx()
axt.plot(np.arange(100), np.arange(100), ls=':', c='r')

img

Unfortunate with with set_ylim it changes the tick-resolution.

enter image description here

Upvotes: 0

Views: 176

Answers (1)

Thomas Kühn
Thomas Kühn

Reputation: 9810

You can set the two y-axes to have equal limits with the command

axt.set_ylim(ax.get_ylim())

after you have performed all plotting commands. Equally, if you only want the lower values (the 0) to coincide, you can do

axt.set_ylim([ax.get_ylim()[0],axt.get_ylim()[1]])

This works because ax.get_ylim() returns a tuple, where the first entry is the lower limit and the second value is the upper limit of the displayed axes range. set_ylim() in turn expects a two-element iterable (e.g. a list or a tuple), which you can construct on the fly.

EDIT:

As pointed out by tmdavison in the comments, one can also just pass one of the limits to set_xlim(), thereby leaving the other limit unchanged (see the documentation for details). This is done with the keywords bottom and top. For the example in the OP, the way to only set the lower limit of the twin axes to 0, the according command would be

axt.set_ylim(bottom=ax.get_ylim()[0])

Upvotes: 2

Related Questions