Home > Enterprise >  Y-axis tick values rounded up to the same value due to formatting in matplotlib
Y-axis tick values rounded up to the same value due to formatting in matplotlib

Time:05-28

I have plotted my figure and formatted the decimal points of the second Y-axis ticks to 0. But the y-axis tick values are rounded up to the same value. I don't want to manually set the tick frequency because the data change in each plot. What can I do to make sure the y-axis only shows '0, 1, 2, 3, 4'. The original y data are all in 'int' format.

Besides, x and y ticks are also not shown in the figure, despite that I put ax.tick_params() in the code. Any help will be much appreciated!

if not yrfullinfo.empty:
    fig, ax1 = plt.subplots()
    
    ax2 = ax1.twinx()
    
    ax1.plot(yrfullinfo['Yr'], yrfullinfo['mean'], label = 'mean', zorder = 10)
    ax1.plot(yrfullinfo['Yr'], yrfullinfo['CI-2.5%'], label = 'CI-2.5%', c = 'darkorange', zorder = 10)
    ax1.plot(yrfullinfo['Yr'], yrfullinfo['CI-97.5%'], label = 'CI-97.5%', c = 'darkorange', zorder = 10)
    ax2.plot(yrfullinfo['Yr'], yrfullinfo['count'], label = 'count', ls = '--', c = 'k', zorder = 0)
    ax1.set_xlabel("Year")
    ax1.set_ylabel("mg/m2/yr")
    ax2.set_ylabel('core count')
    ax1.legend(loc = 2)
    ax2.legend(loc = 9)
    ax1.set_xlim([1690,2010])
    ax1.set_ylim(ymin=0)
    ax2.set_ylim(ymin=0)

    ax1.tick_params(axis="x", direction="out")
    ax1.tick_params(axis="y", direction="inout")
    ax2.tick_params(axis="y", direction="inout")
    
    ax1.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
    ax2.yaxis.set_major_formatter(FormatStrFormatter('%.0f'))
    
    ax1.grid(False)
    ax2.grid(False)

enter image description here

CodePudding user response:

For each of the y-axes (ax1 and ax2), you should set the y-ticks. The ax.plot function will automatically set x and y limits. You can use the same limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim() to discover what limits Matplotlib has already set.

start, end = ax2.get_ylim()
ax2.yaxis.set_ticks(np.arange(start, end, 1.0))  #as you want to set ax2 ticks to 1

Add this code right after ax2.set_ylim(ymin=0) and that should work

My output for some random numbers....as I had set mean for random number between 0 and 1 while the median line was set to random number between 0 and 4, matplotlib chose those limits and the stepsize of 1.0 along with your other code ensured that the ticks were 1 unit apart.

enter image description here

  • Related