【问题标题】:Matplotlib plot dates on x axis with equal spacingMatplotlib 在 x 轴上以相等间距绘制日期
【发布时间】:2021-08-18 10:02:58
【问题描述】:

我正在尝试使用子图在 x 轴上绘制日期,但 x 轴上的间距过于拥挤且无法读取。如何使这个间距同样可行和可读。

下面是我的代码:

def plot_time_series(area):
    df_area =df.loc[df.area== str(area)]
    df_area.reset_index(inplace = True)
    fig, ax = plt.subplots(figsize=(10, 7))
    formatter = DateFormatter('%Y-%m-%d')
    ax.title.set_text(market)
    p1 , = plt.plot(df_area['index'], (df_area.feature1 * 1000), color='#15B01A', label='Feature 1')
    ax.xaxis.set_major_formatter(formatter)
    ax.xaxis.set_tick_params(rotation=30, labelsize=10)
    plt.title(str(market))
    p2 , = plt.plot(df_area['index'], df_area.feature_2, color='red', label='feature_2')
    plt.legend(loc='best')
    lgd  = plt.legend(handles=[p1, p2], title='Legend', bbox_to_anchor=(1.05, 1), loc='upper left')
    plt.show()

当前生成的图:

我需要在 x 轴上以相等的间距和视觉可读的方式绘制日期。如何解决?

【问题讨论】:

    标签: python-3.x matplotlib plot time-series


    【解决方案1】:

    我已经使用 mdates 与 majorlocator 和 majorformatter 来实现这一点,更新功能如下:

    def plot_time_series(area):
        df_area =df.loc[df.area== str(area)]
        df_area.reset_index(inplace = True)
        fig, ax = plt.subplots(figsize=(10, 7))
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
        ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval = 18))
        ax.xaxis.set_tick_params(rotation=30, labelsize=10)
        p1 , = plt.plot(df_area['index'], (df_area.feature1 * 1000), color='#15B01A', label='Feature 1')
        ax.xaxis.set_major_formatter(formatter)
        ax.xaxis.set_tick_params(rotation=30, labelsize=10)
        plt.title(str(market))
        p2 , = plt.plot(df_area['index'], df_area.feature_2, color='red', label='feature_2')
        plt.legend(loc='best')
        lgd  = plt.legend(handles=[p1, p2], title='Legend', bbox_to_anchor=(1.05, 1), loc='upper left')
        plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-09
      • 2012-03-26
      • 1970-01-01
      • 2018-08-31
      相关资源
      最近更新 更多