如何重新排列子图,使一个在另一个下面?

How to rearrange subplots so that one is underneath the other?

我正在尝试对两个地块进行编码,使一个地块位于另一个地块下方。但是,我的代码始终将我的两个绘图并排对齐。 这是我的代码:

import numpy as np
from scipy.integrate import odeint
from numpy import sin, cos, pi, array
import matplotlib
from matplotlib import rcParams
import matplotlib.pyplot as plt
from pylab import figure, axes, title, show
import xlsxwriter

plt.style.use('ggplot')

def deriv(z, t):
    l = 0.25    #unextended length of the spring, in m
    m = 0.25       #mass of the bob, in kg
    k = 29.43      #spring constant, in Nm^-1
    g = 9.81    #gravitational acceleration, in ms^-2
    
    x, y, dxdt, dydt = z
    
    dx2dt2 = (l+x)*(dydt)**2 - k/m*x + g*cos(y)
    dy2dt2 = (-g*sin(y) - 2*(dxdt)*(dydt))/(l+x)
            #equations of motion
    
    return np.array([dxdt, dydt, dx2dt2, dy2dt2])


init = array([0, pi/2, 0, 0])
            #initial conditions (x, y, xdot, ydot)

time = np.linspace(0, 10, 1000)
            #time intervals (start, end, number of intervals)

sol = odeint(deriv, init, time)
            #solving the equations of motion

x = sol[:,0]
y = sol[:,1]

fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True)

ax1.plot(time,x)
ax1.set_ylabel('hi')

ax2.plot(time,y)
ax2.set_ylabel('fds')

plt.plot()

但我一直收到这样的结果:

我试过:

plt.subplot(x)
plt.subplot(y)
plt.show()

但我 运行 遇到了这个错误:

Traceback (most recent call last):
  File "/Users/cnoxon/Desktop/Python/Final code 2 copy 2.py", line 39, in <module>
    plt.subplot(x)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/pyplot.py", line 1084, in subplot
    a = fig.add_subplot(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/figure.py", line 1367, in add_subplot
    a = subplot_class_factory(projection_class)(self, *args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/axes/_subplots.py", line 39, in __init__
    s = str(int(args[0]))
TypeError: only size-1 arrays can be converted to Python scalars
>>> 

我应该如何解决这些问题?替代解决方案同样受到赞赏 - 我对如何创建地块没有偏好;我只想一个在另一个下面。谢谢!

数字在 subplots 中的工作方式是首先提供行数,然后提供列数。要让图彼此下方,您需要 2 行和 1 列。因此你首先必须在 plt.subplots(2, 1)

中写 2 然后写 1
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)

来自官方文档

matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)

您现在的方式是 1 行和 2 列,这就是为什么您会看到它们彼此相邻。

第二种方式使用subplot,其中211表示具有2行、1列和第一个子图的图形,212表示2行、1 列和第二个子图。所以前两位指定行数和列数,第三位指定子图号。

plt.subplot(211)
plt.plot(time,x)
plt.ylabel('hi')

plt.subplot(212)
plt.plot(time,y)
plt.ylabel('fds')