是否可以从现有的matplotlib图形对象创建子图?

时间:2018-12-04 11:15:04

标签: python matplotlib

我有一个具有相同x轴的现有图形的列表,我想将它们堆叠在一个画布上。例如,在这里我分别生成两个图形-如何将它们放在一个图上?

import matplotlib.pyplot as plt

time = [0, 1, 2, 3, 4]
y1 = range(10, 15)
y2 = range(15, 20)

## Plot figure 1
fig1 = plt.figure()
plt.plot(time, y1)

## plot figure 2
fig2 = plt.figure()
plt.plot(time, y2)

## collect in a list
figs = [fig1, fig2]

plt.subplot(1, 1, 1)
## code to put fig1 here

plt.subplot(1, 1, 2)
## code to put fig2 here

1 个答案:

答案 0 :(得分:1)

是:

import matplotlib.pyplot as plt
from matplotlib import gridspec

time = [0, 1, 2, 3, 4]
y1 = range(10, 15)
y2 = range(15, 20)

plt.figure(figsize = (5,10))
fig = gridspec.GridSpec(2, 1, height_ratios=[1,1])

x1 = plt.subplot(fig[0])
plt.plot(time, y1)

x2 = plt.subplot(fig[1])
plt.plot(time, y2)

输出:

enter image description here