【问题标题】:plot major ticks and labels only once per day in Pandas groupby DataFrame在 Pandas groupby DataFrame 中每天仅绘制一次主要刻度和标签
【发布时间】:2016-09-29 15:53:15
【问题描述】:

在 Pandas 中,我有一个按日期时间索引并按日期分组的观察数据框(婴儿奶瓶喂养量):

...
bottles = bottles.set_index('datetime')
bottles = bottles.groupby(bottles.index.date)

我想使用 matplotlib 绘制每天增加的累积值——也就是说,显示每天增加的喂食量并在午夜重置:

ax = plt.gca()
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_minor_locator(mdates.HourLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
bottles['volume'].cumsum().plot(kind='bar', figsize=[16,8])
ax.xaxis.grid(True, which="major")
ax.xaxis.grid(False, which="minor")
ax.yaxis.grid(True)
plt.gcf().autofmt_xdate()
plt.show()

产生:

我只想每天在 x 轴上标记一次日期,并且我还想只在日期边界上绘制一条垂直网格线(每 24 小时)。有关如何修复上述代码的任何建议?

【问题讨论】:

  • pandas 假定条形图是分类图,因此您总是会为显示的每个条形图打勾。我的猜测是,您将不得不直接针对 matplotlib 对象编写绘图,而不是通过 pandas 的界面。

标签: python pandas matplotlib


【解决方案1】:

由于您没有提供任何数据,因此我生成了一些虚拟数据。本质上,您可以通过检索 x 轴上的刻度,然后使每小时刻度标签可见,使标签不可见。

注意:这可以持续几个小时,所以resample 你的数据框在必要时可以持续几个小时。

import random
import pandas
import matplotlib.pyplot as plt

#generate dummy data and df
dates = pd.date_range('2017-01-01', '2017-01-10', freq='H')
df = pd.DataFrame(np.random.randint(0, 10, size=(1, len(dates)))[0], index=dates)
ax = df.groupby(pd.TimeGrouper('D')).cumsum().plot(kind='bar', width=1, align='edge', figsize=[16,8]) #cumsum with daily reset.
ax.xaxis.grid(True, which="major")
#ax.set_axisbelow(True)

#set x-labels to certain date format
ticklabels = [i.strftime('%D') for i in df.index]
ax.set_xticklabels(ticklabels)

#only show labels once per day (at the start of the day)
xticks = ax.xaxis.get_major_ticks()
n=24 # every 24 hours
for index, label in enumerate(ax.get_xaxis().get_ticklabels()):
    if index % n != 0:
        label.set_visible(False)  # hide labels
        xticks[index].set_visible(False)  # hide ticks where labels are hidden

ax.legend_.remove()
plt.show()

结果:

【讨论】:

    猜你喜欢
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    相关资源
    最近更新 更多