由于 matplotlib 中的格式化,Y 轴刻度值四舍五入为相同的值

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

我绘制了我的图形并将 second Y 轴刻度的小数点格式化为 0。但是 y 轴刻度值四舍五入为相同的值。我不想手动设置刻度频率,因为每个图中的数据都会发生变化。我该怎么做才能确保 y 轴仅显示“0、1、2、3、4”。原始y数据都是'int'格式

此外,图中也没有显示 x 和 y 刻度,尽管我在代码中放入了 ax.tick_params()。任何帮助将不胜感激!

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)

对于每个 y-axes(ax1 和 ax2),您应该设置 y-ticks。 ax.plot 函数将自动设置 x 和 y 限制。您可以使用相同的限制,只需更改刻度线的步长,然后您可以使用 ax.get_xlim() 来发现 Matplotlib 已经设置的限制。

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

ax2.set_ylim(ymin=0) 之后添加这段代码应该可以工作

我的一些随机数的输出....因为我将随机数的均值设置为 0 到 1 之间,而中线设置为 0 到 4 之间的随机数,matplotlib 选择了这些限制和 1.0 的步长与您的其他代码一起确保滴答声相隔 1 个单位。