【问题标题】:ticker.MultipleLocator shows wrong xticksticker.MultipleLocator 显示错误的 xticks
【发布时间】:2022-01-22 19:21:51
【问题描述】:
sns.set_style("whitegrid")
bar,ax = plt.subplots(figsize=(32,18))
ax = sns.barplot(x="month_year", y="load", data=df, ci=None, palette="muted", orient='v')
ax.set_xlabel ("Date", fontsize=20)
ax.tick_params(axis="x", labelsize=25, rotation=45)
#ax.xaxis.set_major_locator(ticker.MultipleLocator(base=5))
ax.tick_params(axis="y", labelsize=25)
plt.show()

我想很少可视化 xticks。它看起来像这样:

当我使用ax.xaxis.set_major_locator(ticker.MultipleLocator(base=5)) 代码时,它看起来像这样:

情况是 xticks 出现错误,因为最后日期应该是 2021-12,但它是 2013-4。

我该如何解决?

提前致谢

【问题讨论】:

    标签: python matplotlib seaborn visualization


    【解决方案1】:

    multipleLocator 将刻度间隔设置为 5,但我认为原因是给定的刻度不是以 5 为单位。我相信还有很多其他方法可以做到这一点,但我创建了一个新的刻度间隔和将刻度设置为新的 5 单位间隔。

    import pandas as pd
    import numpy as np
    import seaborn as sns
    
    df = pd.DataFrame({'date': pd.date_range('2011-02-01','2021-12-01', freq='M'),
                       'load': np.random.randint(15,150,130)})
    df['month_year'] = pd.to_datetime(df['date'])
    
    sns.set_style("whitegrid")
    fig,ax = plt.subplots(figsize=(32,18))
    ax = sns.barplot(x="month_year", y="load", data=df, ci=None, palette="muted", orient='v')
    ax.tick_params(axis="x", labelsize=25, rotation=45)
    ax.set_xticks(np.arange(0,130,5))
    ax.set_xticklabels([x.strftime('%Y-%m') for x in df['month_year']][::5])
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      • 2021-11-11
      • 2021-05-25
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多