首页 > 解决方案 > 即使使用命令 MaxNlocator(integer=True) 我也会得到浮点轴

问题描述

我有这个 df 叫normales

      CODIGO         MES  TMAX  TMIN     PP
0     000130       Enero  31.3  23.5   51.1
1     000130     Febrero  31.7  23.8  136.7
2     000130       Marzo  31.8  23.9  119.5
3     000130       Abril  31.5  23.7   55.6
4     000130        Mayo  30.6  23.1   15.6
     ...         ...   ...   ...    ...
4447  158328      Agosto  11.9 -10.6    2.2
4448  158328  Septiembre  13.2  -9.1    1.2
4449  158328     Octubre  14.6  -8.2    4.9
4450  158328   Noviembre  15.4  -7.2   11.1
4451  158328   Diciembre  14.7  -5.3   35.9

使用此代码,我正在绘制时间序列和条形图:

from matplotlib.ticker import MaxNLocator
from matplotlib.font_manager import FontProperties
for code, data in normales.groupby('CODIGO'):
    

    fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, sharex=False, sharey=False,figsize=(20, 15))
    data.plot('MES',["TMAX"], alpha=0.5, color='red', marker='P', fontsize = 15.0,ax=ax1)

    data.plot('MES',["TMIN"], alpha=0.5,color='blue',marker='D', fontsize = 15.0,ax=ax2)

    data.plot('MES',["PP"],kind='bar',color='green', fontsize = 15.0,ax=ax3)
    
    tabla=ax4.table(cellText=data[['TMAX','TMIN','PP']].T.values,colLabels=["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto",
                         "Septiembre","Octubre","Noviembre","Diciembre"],
              rowLabels=data[['TMAX','TMIN','PP']].columns,rowColours =["red","blue","green"],  
        colColours =["black"] * 12,loc="center",bbox = [0.0, -0.5, 1, 1])
    tabla.auto_set_font_size(False)
    tabla.set_fontsize(15)
    tabla.scale(1,2)
    ax4.axis('off')
    
    ax1.set_ylabel("Temperatura\nMáxima °C/mes", fontsize = 15.0)
    ax1.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax2.set_ylabel("Temperatura\nMínima °C/mes", fontsize = 15.0)
    ax2.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax3.set_ylabel("Precipitación mm/mes", fontsize = 15.0)
    ax3.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax1.set_xlabel("")
    ax2.set_xlabel("")
    ax3.set_xlabel("")
    ax4.set_xlabel("")
    

您可以意识到我ax.yaxis.set_major_locator(MaxNLocator(integer=True))在每个轴上都使用整数轴的数字。虽然我正在使用ax.yaxis.set_major_locator(MaxNLocator(integer=True))我正在获取 yaxis 中具有非整数(浮点)值的图形。你知道为什么会这样吗? 在此处输入图像描述 提前致谢。

标签: pythonpandasmatplotlib

解决方案


MaxNLocator文档:

整数布尔值,默认值:False

如果为 True,则刻度将仅采用整数值,前提是在视图限制内至少找到min_n_ticks整数。

……

min_n_ticks int,默认值:2

您需要更改min_n_ticks为,1因为在视图范围内ax2只有一个12整数,即.


推荐阅读