[英]adding dates to x-axis of stacked area chart
我對 Python 還很陌生,我正在嘗試將日期添加到堆積面積圖的底部,但我遇到了一些我無法解決的錯誤。 我正在使用的圖表示例:
到目前為止,我發現https://matplotlib.org/3.1.1/gallery/text_labels_and_annotations/date.html很有幫助,但我無法實現代碼的某些部分,因為我遇到了一些錯誤不能完全解決。
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()
我預計年份會顯示在 x 軸上(我打算將其編輯為以“Mon YYYY”格式顯示),但出現以下錯誤:
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
我真的不知道我在這里做錯了什么。
編輯1:
我的login_month
數據如下所示
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']
的所有鍵,以便您可以看到有效的用法可能是什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.