pythonmatplotlibaxis-labelsmultiple-axesx-axis

Add a tick to top x axis


I do not really understand why this code is not working

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')

My result:

Plot

There should be a red tick in the top x axis.


Solution

  • the issue with your code is twofold:

    1. By using twiny instead of secondary_axis, the upper x-axis will be different to the bottom one, and I assume you want them to be the same. That's extra work to fix, so I used secondary_axis in my example.
    2. This is something I don't know why it happens, but it has happened to me before. When supplying the tick values, the first one is always "ignored", so you have to supply two or more values. I used 0, but you can use anything.

    Here's my code:

    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)
    

    And the resulting plot:

    Resulting plot