你好,我在 Python 中有这段代码:
import numpy as np
import pylab as plt
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*2*np.pi*t)
fig, (ax, ax1, ax2, ax3, ax4, ax5, ax6, ax7) = plt.subplots(8,1)
ax.plot(t, s, 'o', color = "red")
ax1.plot(t, s, 'o', color = "red")
ax2.plot(t, s, 'o', color = "red")
ax3.plot(t, s, 'o', color = "red")
ax4.plot(t, s, 'o', color = "red")
ax5.plot(t, s, 'o', color = "red")
ax6.plot(t, s, 'o', color = "red")
ax7.plot(t, s, 'o', color = "red")
plt.axis([0, 1, -1, 1])
plt.show()
一切正常,但我只想绘制 4x2 而不是 8x1 的图 我尝试将 plt.subplots(8,1) 替换为 plt.subplots(4,2 ) 但我得到 ValueError: need more than 4 values to unpack
我该怎么做才能解决这个问题?
请您参考如下方法:
当您执行 plt.subplots(4,2) 时,您不会得到轴的平面列表。如果你这样做:
fig, axes = plt.subplots(4,2)
print(axes)
您将获得以下内容:
[[<matplotlib.axes._subplots.AxesSubplot object at 0x00000000050CCBA8>
<matplotlib.axes._subplots.AxesSubplot object at 0x00000000059A0F60>]
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000000005A24A58>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000000005A896A0>]
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000000005AC37B8>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000000005B4EFD0>]
[<matplotlib.axes._subplots.AxesSubplot object at 0x0000000005B5FF60>
<matplotlib.axes._subplots.AxesSubplot object at 0x0000000005C18D30>]]
即一个列表,其中每个元素对应于一行子图。因此,如果您这样做:
import numpy as np
import pylab as plt
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*2*np.pi*t)
fig, axes = plt.subplots(4,2)
axes[0][0].plot(t, s, 'o', color = "red")
axes[0][1].plot(t, s, 'o', color = "red")
axes[1][0].plot(t, s, 'o', color = "red")
axes[1][1].plot(t, s, 'o', color = "red")
axes[2][0].plot(t, s, 'o', color = "red")
axes[2][1].plot(t, s, 'o', color = "red")
axes[3][0].plot(t, s, 'o', color = "red")
axes[3][1].plot(t, s, 'o', color = "red")
plt.axis([0, 1, -1, 1])
plt.show()
