João Pedro
João Pedro

Reputation: 167

Matplotlib shared y-axis - one subplot misaligned

I'm plotting 4 subplots in the same row, with the Y-axis shared. However, for some reason, the last subplot is not aligned. Here is the picture:

enter image description here

Doesn't seems to be a problem with the code:

import numpy as np
import matplotlib.pyplot as plt
from functools import partial

t = np.linspace(-10, 10, 10000)

u = lambda x: np.heaviside(x, 0.5)
r = lambda x: np.piecewise(x, [x < 0, x >= 0], [0, lambda z: z])

########################################################################################################################

y = [2*u(t) - 2*u(t-1),
     u(t) - u(t-1),
     2*r(t)*(u(t+10) - u(t-1)),
     2*r(t+1)*(u(t+10) - u(t))]

legend = [r'$f_1(t)$',
          r'$f_2(t)$',
          r'$f_3(t)$',
          r'$f_4(t)$']

fig, ax = plt.subplots(nrows=1, ncols=4, sharey='all',
                       subplot_kw={'xlim': (-1.5, 2.5),
                                   'ylim': (-0.5, 2.5),
                                   'xticks': np.arange(-1, 3),
                                   'yticks': np.arange(-1, 3),
                                   'xlabel': r'$t$'})


for axi, yi, legendi in zip(ax, y, legend):
    axi.plot(t, yi, label=legendi)
    axi.legend()
    axi.grid(True)

Any ideas on how to solve this?

Upvotes: 2

Views: 424

Answers (1)

alexpiers
alexpiers

Reputation: 726

The issue is coming from the yticks parameters; the range you are passing is larger than the ylim range. If you change the subplot keyword args to:

fig, ax = plt.subplots(nrows=1, ncols=4, sharey=True,
                       subplot_kw={'xlim': (-1.5, 2.5),
                                   'ylim': (-0.5, 2.5),
                                   'xticks': np.arange(-1, 3),
                                   'yticks': np.arange(0, 3),
                                   'xlabel': r'$t$'})

You get the following plot: enter image description here

Upvotes: 2

Related Questions