微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

向条形图添加分组刻度

如何解决向条形图添加分组刻度

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

bar chart with 3 hourly ticks

我已经用以下格式格式化了刻度:

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

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

enter image description here

我尝试了多种使用 set_major_locatorset_major_formatter(以及结合主要和次要格式化程序),但似乎我没有正确地接近它,我无法在线查找类似组合蜱的有用示例。

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

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

解决方法

一个想法是设置主要刻度以在每天中午显示日期(%-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)

bar plot with major day ticks,minor hour ticks,and day separators

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。