同一轴上的多个绘图日期具有间距不均匀的刻度和网格

2024-05-15 01:25:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些数据帧,代表前端应用程序中的用户活动。我试图将这些活动绘制在每个用户的单个绘图上,其中每种活动都位于单独的行上。目标是对用户活动有一个良好的纵向视图。我为每个用户创建一个子包,然后为每种类型的活动调用plot_date。我看到的问题是x轴上有多余/错位的记号和网格线。当我增加对plot_date的调用时,这个问题会变得更糟(我的实际代码中有5个不同的调用)。我试过使用和不使用sharex。我试过了。我甚至尝试在不同的地方显式地设置xlim。任何东西都无法消除多余的记号/网格线。我确信我可以通过在代码的最后手动覆盖记号来解决这个问题,但这感觉是错误的。有没有更好的方法来处理这个问题?我觉得这很糟糕

ncols = 2
len_list = 4
nrows  = int(np.ceil(len_list / ncols))
fig, ax = plt.subplots(figsize=(16,2*nrows), nrows=nrows, ncols=ncols, sharex=True, sharey=True)
for i, user in enumerate(sorted(expected_users)[:4]):
    row = int(i/ncols)
    col = i%ncols
    user_paginations = expected_paginations[expected_paginations['action_by'] == user]
    user_actions = expected_actions[expected_actions['action_by'] == user]
    if not user_actions.empty:
        print('actions', user_actions['date'].min(), user_actions['date'].max())
        ax[row,col].plot_date(user_actions['date'], np.random.uniform(0, 0.5, user_actions.shape[0]) + 0, alpha=0.5, label='action')
    if not user_paginations.empty:
        print('pages', user_paginations['date'].min(), user_paginations['date'].max())
        ax[row,col].plot_date(user_paginations['date'], np.random.uniform(0, 0.5, user_paginations.shape[0]) + 1, alpha=0.5, label='paginate')
plt.tight_layout()
fig.autofmt_xdate()

broken_ticks

为了便于参考,我在代码中添加了一些print语句,生成了以下输出:

actions 2019-12-20 07:24:39.362000 2020-01-16 11:14:11.776000
pages 2019-12-20 07:33:58.294000 2020-01-16 07:13:17.629000
actions 2020-01-03 11:20:05.271000 2020-01-16 09:25:21.311000
pages 2020-01-14 13:27:02.093000 2020-01-16 09:18:14.726000
actions 2020-01-08 06:55:40.045000 2020-01-08 06:55:40.775000
actions 2020-01-07 10:04:37.674000 2020-01-08 13:53:58.130000
pages 2020-01-07 09:59:29.376000 2020-01-08 13:34:48.712000

编辑:我想在这里强调的问题是,刻度线的间距不均匀。随着我添加更多数据点,这一点变得更加明显。我附上了一些额外的例子来进一步强调这个问题

对于所有6种活动类型: enter image description here

通过较少的示例,可以看出问题的根源不是用户数量(子批次): enter image description here

我还用一个图重新运行了这个程序,以验证它不是由多个图引起的

再仔细看一看,问题总是发生在每月的第一天。除了第一天,所有日期之间的距离都完全相同

我在https://gist.github.com/mdbecker/727a362ff573a459c5d7a66dfc46836e上发布了一个“最小”数据集和示例代码,您可以使用它来重现这个问题

更新2:将matplotlib更新为3.1.1(从3.0.2版)修复了此错误


Tags: 代码用户actionsdateplotnppagesax

热门问题