【问题标题】:Matplotlib shared y-axis - one subplot misalignedMatplotlib 共享 y 轴 - 一个子图未对齐
【发布时间】:2020-01-06 21:57:20
【问题描述】:

我在同一行中绘制 4 个子图,共享 Y 轴。但是,由于某种原因,最后一个子图没有对齐。这是图片:

代码似乎没有问题:

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)

关于如何解决这个问题的任何想法?

【问题讨论】:

    标签: python matplotlib graph


    【解决方案1】:

    问题来自yticks 参数;您传递的范围大于ylim 范围。如果将 subplot 关键字 args 更改为:

    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$'})
    

    你得到以下情节:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 2015-07-21
      相关资源
      最近更新 更多