绘制两个地块。一个有两个系列(和两个刻度),另一个有两个相同刻度的系列

Plotting two plots. One with two series (and two scales), the other with 2 series on the same scales

我正在绘制一些数据。一个地块在另一个地块下面。顶部图有两个系列,它们具有共享的 x 轴,但在 y 轴上的比例不同。底部图有两个具有相同 x 和 y 轴刻度的系列。

这是我希望制作时的图片:

最上面的情节是我希望的样子。然而,我正在努力获取数据以绘制我的第二个图。我的代码如下所示:

fig, axs = plt.subplots(2, 1, figsize=(11.69, 8.27))

color1 = 'red'
color2 = 'blue'
axs[0].set_title("Energy of an Alpha Particle Against Distance Through a {} Target".format(Sy_t), fontsize=15)
axs[0].set_ylabel("Alpha Energy (MeV)", fontsize=10, color=color1)
axs[0].set_xlabel("Distance travelled through target (cm)", fontsize=10)
axs[0].tick_params(axis='y', colors=color1)
axs[0].grid(lw=0.2)
axs[0].plot(dc['sum'], dc.index, marker='+', lw=0.2, color=color1)
axs[1] = axs[0].twinx()

#ax2.set_title("Stopping Power Against Distance through a {} Target".format(Sy_t), fontsize=15)
axs[1].set_ylabel("dE/dx (MeV/cm)", fontsize=10, color=color2)
axs[1].set_xlabel("Distance travelled through target (cm)", fontsize=10)
axs[1].plot(dc['sum'], dc['dydsum'], marker='+', lw=0.2, color=color2)
axs[1].tick_params(axis='y', colors=color2)
axs[1].grid(lw=0.2)
fig.tight_layout()

axs[2].set_title('Cross-Section Plots overall and for the product')
axs[2].set_ylabel('Cross-Section (mb)')
axs[2].set_xlabel('Energy (MeV)')
axs[2].plot(Sig_sum)
axs[2].plot(Sig_prod)
plt.show()

我得到的错误是:

IndexError: index 2 is out of bounds for axis 0 with size 2 

上图的数据来自数据框。底部的两个系列具有相同的 x 和 y 比例,其中一个日期框如下所示:

1        0.001591
2        0.773360
3       28.536766
4      150.651937
5      329.797010
6      492.450824
7      608.765402
8      697.143340
9      772.593010
10     842.011451
11     900.617395
12     947.129704
13     984.270901
14    1015.312625
15    1041.436808
16    1062.700328
17    1079.105564
18    1091.244022
19    1100.138834
20    1107.206041
21    1113.259507
22    1118.579315
23    1123.164236
24    1127.014592
25    1129.558439
26    1130.390331
27    1129.917985
28    1128.069117
29    1125.184650
30    1121.497063
31    1117.341899
32    1112.556194
33    1108.158215
34    1103.083775
35    1097.872010
36    1092.889581
37    1087.439353
38    1081.922461
39    1076.163363
40    1070.421916

当我尝试自己绘制下图时,它的图形如下所示:

你可能会从发生的事情的一些分解中受益。一开始,你调用

fig, axs = plt.subplots(2, 1)

将图形分成两个子图(技术上 axes.Axes class)。 axs 是一个包含两个轴对象的数组。

稍后,你做

axs[1] = axs[0].twinx()

它做了两件事:它创建了第三个 axes.Axes 对象(在顶部子图的顶部)并更改 axs[1] 的值以引用该对象而不是底部子图。然后你就没有(简单的)方法来访问底部的子图(并且试图访问 axs 的 out-of-bounds 索引会使错误立即发生)。

可能的修复:

fig, axs = plt.subplots(2, 1, ...)
topleftax = axs[0]
toprightax = axs[0].twinx()
bottomax = axs[1]
# and replace in the code that comes thereafter:
# axs[0] -> topleftax
# axs[1] -> toprightax
# axs[2] -> bottomax