使用 matplotlib 为子图设置相同的比例但不同的限制

时间:2021-02-05 10:28:06

标签: python matplotlib plot

我希望我的两个子图的缩放比例相同,以使它们具有可比性,但应自动设置限制。 这是一个小的工作示例:

import matplotlib.pyplot as plt
import numpy as np

time = range(20)
y1 = np.random.rand(20)*2
y2 = np.random.rand(20) + 10

fig, axes = plt.subplots(2, figsize=(10,4), sharex=True, sharey=True)
# OPTION 2: fig, axes = plt.subplots(2, figsize=(10,4))
axes[0].plot(time, y1)
axes[1].plot(time, y2)

plt.show()

情节如下:

enter image description here

如果选项 2 没有注释,它看起来像这样:

enter image description here

在第二个图中,y1 和 y2 看起来同样嘈杂,这是错误的,但在图 1 中,轴限制太高/太低。

1 个答案:

答案 0 :(得分:0)

我不知道这样做的自动缩放功能(这并不意味着它不存在 - 实际上,我会惊讶它不存在)。不过写起来也不难:

import matplotlib.pyplot as plt

#data generation
import numpy as np
np.random.seed(123)
time = range(20)
y1 = np.random.rand(20)*2
y2 = np.random.rand(20) + 10
y3 = np.random.rand(20)*6-12

#plot data
fig, axes = plt.subplots(3, figsize=(10,8), sharex=True)
for ax, y in zip(axes, [y1, y2, y3]):
    ax.plot(time, y)

#determine axes and their limits 
ax_selec = [(ax, ax.get_ylim()) for ax in axes]

#find maximum y-limit spread
max_delta = max([lmax-lmin for _, (lmin, lmax) in ax_selec])

#expand limits of all subplots according to maximum spread
for ax, (lmin, lmax) in ax_selec:
    ax.set_ylim(lmin-(max_delta-(lmax-lmin))/2, lmax+(max_delta-(lmax-lmin))/2)

plt.show()

示例输出:

enter image description here

相关问题