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

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

产生:python - DataFrame每天仅绘制一次主要的刻度和标签-LMLPHP
我只想把X轴上的日期标注为每天一次,我还想在日期边界上画一条垂直网格线(每24小时)。对于如何修复上述代码有什么建议吗?

最佳答案

因为你没有提供任何数据,所以我生成了一些虚拟数据。本质上,您可以通过检索x轴上的刻度,使标签不可见,从而使每小时可见的图像变得清晰可见。
注意:这会持续数小时,因此如果需要,您的数据帧会持续数小时。

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

结果:
resample

关于python - DataFrame每天仅绘制一次主要的刻度和标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37549017/

10-12 19:24