python - adding dates to x-axis of stacked area chart
问题描述
I'm fairly new to Python and I'm trying to add dates to the bottom of a stacked area chart, but I'm running into some errors that I can't resolve. Example of the chart I'm working with:
So far, I've found https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/date.html helpful, but I'm unable to implement some portions of the code because I'm running into some errors that I can't quite resolve.
area_plot = (df.pivot(index='login_month',
columns='user_month_created',
values='cumulative_logins')
.plot.area(figsize=(20,18))
)
#labels
plt.title('cumulative monthly logins by user creation cohort month')
plt.xlabel('login month')
plt.ylabel('cumulative monthly logins (in tens of millions)')
#ticks
# plt.xticks(x, 'bbbb')
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
years_fmt = mdates.DateFormatter('%Y')
# format the ticks
area_plot.xaxis.set_major_locator(years)
area_plot.xaxis.set_major_formatter(years_fmt)
area_plot.xaxis.set_minor_locator(months)
# round to nearest years.
datemin = np.datetime64(df['login_month'][0], 'Y')
datemax = np.datetime64(df['login_month'][-1], 'Y') + np.timedelta64(1, 'Y')
area_plot.set_xlim(datemin, datemax)
plt.xticks()
plt.yticks(np.arange(0, 11000000, 250000))
plt.grid(True)
plt.plot()
I expected the years to show up on the x-axis (and I was going to edit it to appear in a "Mon YYYY" format), but I get the error below:
KeyError -1 ---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-102-5fb53d3f1bb7> in <module>
24 # round to nearest years.
25 datemin = np.datetime64(df['login_month'][0], 'Y')
---> 26 datemax = np.datetime64(df['login_month'][-1], 'Y') + np.timedelta64(1, 'Y')
27 area_plot.set_xlim(datemin, datemax)
28
/opt/conda/envs/python3/lib/python3.6/site-packages/pandas/core/series.py in __getitem__(self, key)
765 key = com._apply_if_callable(key, self)
766 try:
--> 767 result = self.index.get_value(self, key)
768
769 if not is_scalar(result):
/opt/conda/envs/python3/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
3116 try:
3117 return self._engine.get_value(s, k,
-> 3118 tz=getattr(series.dtype, 'tz', None))
3119 except KeyError as e1:
3120 if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: -1
I don't really know what I'm doing wrong here.
Edit 1:
My login_month
data looks like the following
signup_month login_month cumulative_logins
0 2016-01 2016-02 16
1 2016-01 2016-03 20
2 2016-01 2016-04 26
3 2016-01 2016-05 29
4 2016-02 2016-03 10
5 2016-02 2016-04 15
6 2016-02 2016-05 20
7 2016-03 2016-04 13
8 2016-03 2016-05 23
9 2016-04 2016-05 35
解决方案
例外:
KeyError: -1
表示-1
不是 的有效键df['login_month']
。我不熟悉df
为您创建的模块,但我建议您查看其文档或转储所有df['login_month']
's 键,以便您了解可能的有效用法。
推荐阅读
- javascript - 将 html 选择下拉列表转换为单个按钮导航栏
- javascript - 如何获取文本区域的值并检查它是否为空
- windows - 如何从命令行显示“设置”窗口以选择在通知区域中显示哪些图标?
- javascript - EventSource.addEventListener() 在 iOS 14 上不起作用
- node.js - 有没有办法将 ShareDB 与 AWS API Gateway WebSocket 一起使用?
- php - Laravel 8 迁移“一般错误:1215 无法添加外键约束”
- python - 在 VS Code 终端中执行程序时,Matplotlib 不显示绘图
- puppeteer - 是否可以使用 CodeceptJS + PlayWright 或 CodeceptJS + Puppeteer 启动 Chrome 浏览器
- php - Laravel 队列不起作用,我收到错误消息
- r - 从 selectInput 或 sliderInput 获取参数并单击 ActionButton 后,如何在 R Shiny 中执行函数?