使用fig.add_axes创建的子图中的标签排序

问题描述 投票:0回答:1

我是python的新手,我正在玩matplotlib。下面是我的情节代码,如下图所示。

import matplotlib.pyplot as plt
f = plt.figure(figsize=(15, 15))

ax1 = f.add_axes([0.1, 0.5, 0.8, 0.5],
                   xticklabels=[])
ax2 = f.add_axes([0.1, 0.4, 0.8, 0.1])

ax1.plot(particles[0, :, 0])
ax1.plot(particles[1, :, 0])
ax2.plot(distances[:])

# Prettifying the plot
plt.xlabel("t", fontsize=25)     
plt.tick_params(                 # modifying plot ticks
    axis='x', 
    labelsize=20)
plt.ylabel("x", fontsize=25)     
plt.tick_params(                 # modifying plot ticks
    axis='y',
    labelsize=20)

# Plot title
plt.title('Harmonic oscillator in ' + str(dim) + 'D with ' + str(num_step) + ' timesteps', fontsize=30)

# Saving the plot
#plt.savefig("results/2D_dif.png")

这两个图表具有我想要的尺寸和位置,但正如您所看到的,标签和标题都是关闭的。我希望有相同的标签样式,如应用于底部图,上图的y标签读数为“x”,标题“Harmonic oscillator ...”位于第一个图表的顶部。

我非常感谢你的帮助!

matplotlib plot axis-labels
1个回答
0
投票

这里plt正在最近创建的轴实例(在本例中为ax2)。这就是ax1字体没有变化的原因!

所以,要获得你想要的东西,你需要明确地对ax1ax2采取行动。像下面这样的东西应该做的伎俩:

for ax in ax1, ax2:
    # Prettifying the plot
    ax.set_xlabel("t", fontsize=25)     
    ax.tick_params(                 # modifying plot ticks
        axis='x', 
        labelsize=20)
    ax.set_ylabel("x", fontsize=25)     
    ax.tick_params(                 # modifying plot ticks
        axis='y',
        labelsize=20)

    # Plot title
    ax.set_title('Harmonic oscillator in ' + str(dim) + 'D with ' + str(num_step) + ' timesteps', fontsize=30)
© www.soinside.com 2019 - 2024. All rights reserved.