【问题标题】:Issues plotting every nth date xaxis绘制每隔 n 个日期 xaxis 的问题
【发布时间】:2021-11-23 05:10:39
【问题描述】:

我有一个这样的 df:

     level_0      DATE        ONI  positive  YEAR
686      sst 1960-03-15 -0.364453     False  1960
687      sst 1960-04-15 -0.366851     False  1960
688      sst 1960-05-15 -0.321550     False  1960
689      sst 1960-06-15 -0.382227     False  1960
690      sst 1960-07-15 -0.374074     False  1960
     ...        ...       ...       ...   ...
1363     sst 2016-08-15 -0.597598     False  2016
1364     sst 2016-09-15 -0.784883     False  2016
1365     sst 2016-10-15 -0.900240     False  2016
1366     sst 2016-11-15 -1.006226     False  2016
1367     sst 2016-12-15 -1.065392     False  2016

[682 rows x 5 columns]

我想每隔 n 年用 xaxis 绘制我的数据,所以我做了这个代码:

fig = plt.figure('ONI', figsize=(15,20), dpi=200)
ax = fig.add_axes([0.15,0.15,0.7,0.7])


df_oni.plot(x='DATE',y="ONI",kind='bar', alpha=0.5, color=df_oni.positive.map({True: 'r', False: 'b'}),ax=ax)


date_form = DateFormatter("%Y")
ax.xaxis.set_major_formatter(date_form)
ax.xaxis.set_major_locator(mdates.YearLocator(base=5))

ax.xaxis.set_tick_params(rotation=0)

ax.set_title("Indice ONI",fontsize= 14,fontweight="bold")
# Define the date format

ax.set_ylabel("Valor del Índice\n", fontsize = 10.0)
ax.yaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=1))

ax.set_xlabel("")

我不明白为什么即使使用 ax.xaxis.set_major_locator(mdates.YearLocator(base=5)) 我在 xaxis 中只有 1 年就得到了这个数字:

你愿意帮助我吗?提前致谢。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    这与pandas 生成bar 图的方式有关,它只是索引x 位置(验证:ax.get_xlim() 给出(-0.5, 681.5))。

    最简单的解决方法是直接使用matplotlib:

    ax.bar(df_oni.DATE,df_oni.ONI, width=20, alpha=0.5, color=df_oni.positive.map({True: 'r', False: 'b'}))
    

    (您需要将条形宽度增加到 20 以获得更好的视觉效果)

    例子:

    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    import matplotlib.dates as mdates
    import matplotlib.ticker as mticker
    
    fig = plt.figure('ONI', figsize=(15,20), dpi=200)
    ax = fig.add_axes([0.15,0.15,0.7,0.7])
    
    df_oni = pd.DataFrame({'DATE': pd.date_range('1960-03', periods=682, freq='M'),
                           'ONI': (np.random.rand(682) - .5)*5})
    df_oni['positive'] = df_oni.ONI>0
    
    ax.bar(df_oni.DATE,df_oni.ONI, width=20, alpha=0.5, color=df_oni.positive.map({True: 'r', False: 'b'}))
    
    ax.xaxis.set_major_locator(mdates.YearLocator(base=5))
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y"))
    ax.xaxis.set_tick_params(rotation=0)
    
    ax.yaxis.set_major_locator(mticker.MaxNLocator(integer=True, min_n_ticks=1))
    
    ax.set_title("Indice ONI",fontsize= 14,fontweight="bold")
    ax.set_ylabel("Valor del Índice\n", fontsize = 10.0)
    ax.set_xlabel("")
    

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多