【问题标题】:Adding grouping ticks to a bar chart将分组刻度添加到条形图
【发布时间】:2021-07-15 05:48:49
【问题描述】:

我有一个由 pandas DataFrame 创建的图表,如下所示:

我已将刻度格式化为:

ax = df.plot(kind='bar')
ax.set_xticklabels(df.index.strftime('%I %p'))

但是,我想添加第二组较大的刻度,以实现这种效果:

我尝试了许多使用 set_major_locatorset_major_formatter 的变体(以及结合主要和次要格式化程序),但似乎我没有正确处理它,我无法找到有用的例子在线也有类似的组合滴答声。

有人对如何实现类似于底部图像的东西有建议吗?

数据框有一个日期时间索引并且是分箱数据,来自df.resample(bin_size, label='right', closed='right').sum())

【问题讨论】:

    标签: pandas matplotlib bar-chart xticks


    【解决方案1】:

    一个想法是设置主要刻度以在每天中午显示日期 (%-d-%b),并带有一些填充(例如,pad=40)。这将在中午留下一个小刻度间隙,因此为了保持一致性,您可以仅在奇数时间设置小刻度并给它们rotation=90

    请注意,这使用了 matplotlib 的 bar(),因为 pandas 的 plot.bar() 不能很好地处理日期格式。

    import matplotlib.dates as mdates
    
    # toy data
    dates = pd.date_range('2021-08-07', '2021-08-10', freq='1H')
    df = pd.DataFrame({'date': dates, 'value': np.random.randint(10, size=len(dates))}).set_index('date')
    
    # pyplot bar instead of pandas bar
    fig, ax = plt.subplots(figsize=(14, 4))
    ax.bar(df.index, df.value, width=0.02)
    
    # put day labels at noon
    ax.xaxis.set_major_locator(mdates.HourLocator(byhour=[12]))
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%-d-%b'))
    ax.xaxis.set_tick_params(which='major', pad=40)
    
    # put hour labels on odd hours
    ax.xaxis.set_minor_locator(mdates.HourLocator(byhour=range(1, 25, 2)))
    ax.xaxis.set_minor_formatter(mdates.DateFormatter('%-I %p'))
    ax.xaxis.set_tick_params(which='minor', pad=0, rotation=90)
    
    # add day separators at every midnight tick
    ticks = df[df.index.strftime('%H:%M:%S') == '00:00:00'].index
    arrowprops = dict(width=2, headwidth=1, headlength=1, shrink=0.02)
    for tick in ticks:
        xy = (mdates.date2num(tick), 0) # convert date index to float coordinate
        xytext = (0, -65)               # draw downward 65 points
        ax.annotate('', xy=xy, xytext=xytext, textcoords='offset points',
                    annotation_clip=False, arrowprops=arrowprops)
    

    【讨论】:

    • 谢谢,很干净。您是否有想法以一种简洁的方式添加示例中显示的细长刻度?
    • @Grismar 嗯,唯一想到的是手动 annotate 行。我更新了代码以提取午夜位置并在这些位置的 x 轴下方绘制线条。
    • 谢谢,我很感激 - 我考虑过在次要刻度位置覆盖的时间,但不能真正想出一个好的解决方案。它可能必须这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 2020-05-02
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 2020-08-14
    相关资源
    最近更新 更多