【问题标题】:Is it possible to control xlabel stepping label in subplot?是否可以在子图中控制 xlabel 步进标签?
【发布时间】:2019-05-25 12:19:14
【问题描述】:

我相信这是关于子情节的老问题。但是,我无法找到我的答案。

问题:
是否可以让我的subplot 相同地踩x-label

y_label = 'db_server_6a_2018_df_IL1-A'

f, ax_list = plt.subplots(12, 1, gridspec_kw = {
    'height_ratios': [20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20],
    'width_ratios': [30]
}, figsize=(20, 40))
for month in range(1, 12 + 1):
    start_dt = datetime.datetime(2018, month, 1)
    end_dt = start_dt + relativedelta(months=1)
    window_df = df[(start_dt < df['Time']) & (df['Time'] <= end_dt)]

    ax = ax_list[month-1]
    ax.plot(window_df['Time'], window_df[y_label])
    ax.set_ylabel(start_dt.strftime('%B'))
    ax.set_xlabel('datetime')
f.savefig(y_label + '.png')

这是输出

【问题讨论】:

    标签: python matplotlib label subplot


    【解决方案1】:

    您是否已经尝试设置 xticks() 和 xlim(),即分别为每个子图设置应放置刻度的新位置列表并设置新 x 轴限制的元组?

    xticks documentation

    xlim documentation

    它们也应该适用于子图。

    另一种解决方案可能是使用:

    plt.subplot(something, sharex=ax, sharey=ax)
    

    在哪里,如文档中所述

    sharex, sharey : Axes, optional
    Share the x or y axis with sharex and/or sharey. 
    The axis will have the same limits, ticks, and scale as the axis of the shared axes.
    

    附:我不能写评论,因为我没有足够的声誉。

    【讨论】:

      【解决方案2】:

      感谢@ElidorDD 的回答。我刚刚从他那里知道了正确的措辞。这是我的问题的答案,它继承自 matplotlib.axes.Axes 类而不是 matplotlib.pyplot

      ax.xaxis.grid(True)
      ax.xaxis_date()
      ax.set_xticks([datetime.datetime(2018, month,1), 
                     datetime.datetime(2018, month, 7),
                     datetime.datetime(2018, month, 14),
                    datetime.datetime(2018, month, 21),
                    datetime.datetime(2018, month, 28)])
      monthyearFmt = mdates.DateFormatter('%Y-%m-%d')
      ax.xaxis.set_major_formatter(monthyearFmt)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-29
        相关资源
        最近更新 更多