Python 在顶部x轴上添加记号

Python 在顶部x轴上添加记号,python,matplotlib,axis-labels,multiple-axes,x-axis,Python,Matplotlib,Axis Labels,Multiple Axes,X Axis,我真的不明白为什么这个代码不起作用 fig, ax = plt.subplots() ax.plot(Vg_vec, sigma_i) ax.set_xlabel('$V_\mathrm{g}$ ($\mathrm{V}}$)') ax.set_ylabel('$\sigma_\mathrm{i}$ ($\mathrm{C/m^2}$)') peaks, _ = find_peaks(sigma_i, height=0.006415) plt.axvline(Vg_vec[peaks], co

我真的不明白为什么这个代码不起作用

fig, ax = plt.subplots()
ax.plot(Vg_vec, sigma_i)
ax.set_xlabel('$V_\mathrm{g}$ ($\mathrm{V}}$)')
ax.set_ylabel('$\sigma_\mathrm{i}$ ($\mathrm{C/m^2}$)')

peaks, _ = find_peaks(sigma_i, height=0.006415)
plt.axvline(Vg_vec[peaks], color='red')

ax2 = ax.twiny()
ax2.set_xticks(Vg_vec[peaks])
ax2.tick_params(axis='x', colors='red')

顶部x轴上应有一个红色记号


谢谢

您的代码有两个问题:

  • 通过使用
    twiny
    而不是
    secondary_轴
    ,上部x轴将不同于底部x轴,我假设您希望它们相同。这是需要修复的额外工作,因此我在示例中使用了
    次轴
  • 这是我不知道为什么会发生的事情,但我以前也发生过。提供勾号值时,第一个值总是“忽略”,因此必须提供两个或多个值。我用了
    0
    ,但你可以用任何东西
  • 这是我的密码:

    fig, ax = plt.subplots()
    ax.plot(Vg_vec, sigma_i)
    ax.set_xlabel('$V_\mathrm{g}$ ($\mathrm{V}}$)')
    ax.set_ylabel('$\sigma_\mathrm{i}$ ($\mathrm{C/m^2}$)')
    
    peaks, _ = find_peaks(sigma_i, height=None)
    plt.axvline(Vg_vec[peaks], color='red')
    
    ax2 = ax.secondary_xaxis('top')
    ax2.tick_params(axis='x', color='red')
    ax2.set_xticks([0, *Vg_vec[peaks]], minor=False)
    
    结果是:

    你喜欢什么?