首页 > 解决方案 > 将 DataFrame(具有日期索引)绘制为条形图

问题描述

我在这个领域是全新的,几乎所有的事情对我来说仍然是一个谜。

我有以下数据框:

            usersPerWeek date
      date      
2018-03-07  127          2018-03-07
2018-03-14  3177         2018-03-14
2018-03-21  8758         2018-03-21
2018-03-28  16770        2018-03-28
2018-04-04  17964        2018-04-04

我试图将其绘制为一个简单的条形图:

import pandas as pd
import matplotlib.pyplot as plt
figPerWeek = plt.figure(dpi=80, figsize=(8,1))
axis = figPerWeek.add_subplot(1,1,1)
axis.bar(x=data.index, height=data.usersPerWeek)

这会导致错误消息Axis must have频率set to convert to Periods

当我添加时(就在调用之前axis.bar

axis.xaxis_date()

然后我收到错误消息'Period' object has no attribute 'toordinal'

我希望我错过了一些非常简单的东西,但到目前为止谷歌一直没有帮助。

干杯

标签: pythonpython-3.xpandasmatplotlib

解决方案


它似乎在下面的示例中有效。

from numpy.random import randint
import pandas as pd
import matplotlib.pyplot as plt

# Create data frames for the example
rng = pd.date_range('3/7/2018 00:00', periods=10, freq='1w')
df = pd.DataFrame({'usersPerWeek': randint(10, 200, 10)}, index=rng)

figPerWeek = plt.figure(dpi=80, figsize=(8,1))
axis = figPerWeek.add_subplot(1,1,1)
axis.bar(x=df.index, height=df.usersPerWeek)
plt.ylabel('usersPerWeek')
plt.show()

在此处输入图像描述


推荐阅读