Matplotlib 两个X轴位置切换

Matplotlib two X axis position switching

我想绘制一个有两个 X 轴的图。

但我想将主机x轴设置为顶部,另一个x轴设置为底部。

我试过了:

    axs[i].barh(bins[:len(count_vol)], count_vol, align='edge', color='black', height = 10) # horizontal bar plot
    axs[i].set_xlabel('concentration (n/m3)')
    axs[i].set_ylabel('depth (m)')
    axs[i].invert_yaxis()
    axs[i].set_title(org, y =1.0) # subplot title
    axs[i].xaxis.set_major_formatter(FormatStrFormatter('%.2f'))
    axs[i].xaxis.tick_top() # x axis to top of the subplot

    #plt.show()


    
    # add environmental data
    temp_ax = axs[i].twiny()
    temp_ax.plot(temperature, depth, color='red')
    temp_ax.set_xlabel('temperature', color='red')
    temp_ax.xaxis.tick_bottom() x axis to botton of the subplot

当我激活 'plt.show()' 时,主机 x 轴位于我想要绘制的顶部。 但是在我 运行 上面的整个脚本之后,两个 x 轴都在底部。

我的代码有什么问题?

有多种方法可以在顶部添加额外的 x 轴。

ticks and labels are with the wrong position

我想 temp_ax.xaxis.tick_bottom() 是多余的。

import matplotlib.pyplot as plt
import numpy as np


x = np.arange(10)

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


# secondary axis

axs[0].plot(x)
axs[0].set_xlabel('label bottom')
secax = axs[0].secondary_xaxis('top')
secax.set_xlabel('label top')

# twiny()

axs[1].set_xlabel('label bottom')
twax = axs[1].twiny()
twax.set_xlabel('label top')


# handle properties

axs[2].xaxis.tick_top()
axs[2].xaxis.set_label_position('top')
axs[2].set_xlabel('label top')

plt.show()