在Python中绘制子图matplotlib

nkoocmlb  于 2023-06-30  发布在  Python
关注(0)|答案(1)|浏览(109)

我有一个问题,试图绘制6个数字在2列,3行的方式。我有以下代码:

fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(nrows=3, ncols=2, sharex=True)

ax1.plot(df_truth.index, df_truth[stat], label = 'Fine')
ax1.plot(df_truth.index, df_Obs[stat], label = 'Observation')
ax1.plot(df_truth.index, df_T12_0hr[stat], label = 'T12_0hr')

ax2.plot(df_truth.index, df_truth[stat], label = 'Fine')
ax2.plot(df_truth.index, df_Obs[stat], label = 'Observation')
ax2.plot(df_truth.index, df_T12_12hr[stat], label = 'T12_12hr')

ax3.plot(df_truth.index, df_truth[stat], label = 'Fine')
ax3.plot(df_truth.index, df_Obs[stat], label = 'Observation')
ax3.plot(df_truth.index, df_T12_24hr[stat], label = 'T12_24hr')

ax4.plot(df_truth.index, df_truth[stat], label = 'Fine')
ax4.plot(df_truth.index, df_Obs[stat], label = 'Observation')
ax4.plot(df_truth.index, df_T3_0hr[stat], label = 'T3_0hr')

ax5.plot(df_truth.index, df_truth[stat], label = 'Fine')
ax5.plot(df_truth.index, df_Obs[stat], label = 'Observation')
ax5.plot(df_truth.index, df_T12_0hr[stat], label = 'T3_12hr')

ax6.plot(df_truth.index, df_truth[stat], label = 'Fine')
ax6.plot(df_truth.index, df_Obs[stat], label = 'Observation')
ax6.plot(df_truth.index, df_T3_24hr[stat], label = 'T3_24hr')
 
plt.savefig(figDir+stat+'_watlev_ts.png', bbox_inches = 'tight', pad_inches = 0.02)
plt.close()
print('Plotting ' + str(stat) )

无论我尝试什么,我都会得到一个错误,说要解包的值太多或太少。我所尝试的:

fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(nrows=3, ncols=2, sharex=True)
fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(3, 2, sharex=True)
fig, ax1, ax2, ax3, ax4, ax5, ax6 = plt.subplots(3,2, sharex=True)
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(3,2, sharex=True)
fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(6, sharex=True)
fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(3, 2)
fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(3, 2, sharex=True)
fig, ax1, ax2, ax3, ax4, ax5, ax6 = plt.subplots(nrows=3, ncols=2, sharex=True)

这是可行的,但只给我一列

fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(6, sharex=True)
tpxzln5u

tpxzln5u1#

axes返回值是一个维数为:rows x cols

>>> fig, axes = plt.subplot(nrows=3, ncols=2)
>>> type(axes)
numpy.ndarray
>>> axes.shape
(3, 2)

因此,您可以使用单个变量并对其进行索引(例如axes[0][1])或指定正确的尺寸/嵌套以进行拆包:

fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6)) = plt.subplots(nrows=3, ncols=2)

相关问题