简体   繁体   English

由于 matplotlib 中的格式设置,Y 轴刻度值向上舍入到相同的值

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

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.我已经绘制了我的数字并将第二个Y 轴刻度的小数点格式化为 0。但是 y 轴刻度值被四舍五入到相同的值。 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'.我该怎么做才能确保 y 轴仅显示“0、1、2、3、4”。 The original y data are all in 'int' format.原始 y 数据都是 'int' 格式。

Besides, x and y ticks are also not shown in the figure, despite that I put ax.tick_params() in the code.此外,图中也没有显示 x 和 y 刻度,尽管我在代码中放入了 ax.tick_params()。 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)

在此处输入图像描述

For each of the y-axes (ax1 and ax2), you should set the y-ticks.对于每个 y 轴(ax1 和 ax2),您应该设置 y 刻度。 The ax.plot function will automatically set x and y limits. ax.plot 函数将自动设置 x 和 y 限制。 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.您可以使用相同的限制,只需更改刻度线的步长,然后您可以使用 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

Add this code right after ax2.set_ylim(ymin=0) and that should workax2.set_ylim(ymin=0)之后添加此代码,这应该可以工作

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.我的一些随机数的输出....因为我设置了 0 到 1 之间的随机数的平均值,而中线设置为 0 到 4 之间的随机数,matplotlib 选择了这些限制和 1.0 的步长以及其他代码确保蜱虫相隔 1 个单位。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM