在Pandas groupby DataFrame中每天只绘制一次主刻度和标签

时间:2016-05-31 14:52:20

标签: python pandas matplotlib

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

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

我想使用matplotlib绘制累积值,因为它们每天都会增加 - 也就是说,显示每天增加并在午夜重置的Feed数量:

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()

产生:plot

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

1 个答案:

答案 0 :(得分:0)

由于您没有提供任何数据,我生成了一些虚拟数据。实质上,您可以通过检索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()

结果: Result