【问题标题】:How to force AxesSubplot to use integer tick labels如何强制 AxesSubplot 使用整数刻度标签
【发布时间】:2020-10-02 23:18:22
【问题描述】:

我正在努力将 Integerlabels 正确应用于 AxesSubplot 对象。不知何故,所有其他流行的解决方案都不起作用。我认为这与 Pandas 的绘图方式与 Matplotlib 本地绘制数据框的方式有关。

查看文档时,提到防止using the optional parameter x_compat 调整分辨率,如下所示:

df['A'].plot(x_compat=True)

但是这只会给我一个错误,而且我在pandas 1.1.2 docs 中也找不到这个参数。

这是产生情节的代码:

def count_id(id_val):
    plot = df[df['ID']==id_val]['TRANSCRIPTION_STRING'].value_counts().plot(kind='bar')
    plot.set_xticklabels(plot.get_xticklabels(), rotation=40, ha ='right')
    print(type(plot))

我找到了this answer,但由于以下原因没有帮助:

  • 它使用.gca() 对我的情况抛出错误。
  • 它专门使用matplotlib 而不是pandas.plot,这在引擎盖下是相同的,但几乎没有非常不同的文档,并且对于我的情况并不明显。更有经验的用户可能会有所不同。

这是一个很好的建议,我看到了相似之处,但我非常想在询问之前发现它有帮助,但它没有帮助。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    你可以使用:

    from matplotlib.ticker import MaxNLocator
    
    plot.yaxis.set_major_locator(MaxNLocator(integer=True))
    

    MaxNLocator 是刻度的默认 'locator'。您还可以强制一些固定的倍数,例如set_major_locator(MultipleLocater(1)).

    PS:pandasplot函数返回值的常用变量名是ax。这更清楚地表明标准的 matplotlib 函数可用于自定义绘图。

        ax = df[df['ID']==id_val]['TRANSCRIPTION_STRING'].value_counts().plot(kind='bar')
        ax.set_xticklabels(plot.get_xticklabels(), rotation=40, ha ='right')
        ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    
    

    【讨论】:

      猜你喜欢
      • 2015-09-04
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 2021-11-11
      • 2015-09-02
      • 1970-01-01
      • 2021-06-14
      相关资源
      最近更新 更多