你好,我有这段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(4,2)替换plt.subplots(8,1),但是我得到了ValueError: need more than 4 values to unpack
我该如何解决这个问题呢?
发布于 2018-04-11 17:01:44
当您执行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()您将获得所需的4x2:

https://stackoverflow.com/questions/49770677
复制相似问题