【发布时间】:2020-02-22 07:10:19
【问题描述】:
我试图在 x 轴上以“Mon YYYY”格式显示月份和年份,但到目前为止我只能显示年份。
我尝试过使用
的变体ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_minor_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%b'))
没有成功。
这是df['login_month'](我试图显示为 x 轴)的样子:
index login_month
0 2016-01-01 00:00:00
1 2016-02-01 00:00:00
2 2016-03-01 00:00:00
3 2016-04-01 00:00:00
4 2016-05-01 00:00:00
5 2016-06-01 00:00:00
6 2016-07-01 00:00:00
7 2016-08-01 00:00:00
8 2016-09-01 00:00:00
9 2016-10-01 00:00:00
10 2016-11-01 00:00:00
11 2016-12-01 00:00:00
12 2017-01-01 00:00:00
13 2017-02-01 00:00:00
14 2017-03-01 00:00:00
15 2017-04-01 00:00:00
16 2017-05-01 00:00:00
17 2017-06-01 00:00:00
18 2017-07-01 00:00:00
19 2017-08-01 00:00:00
20 2017-09-01 00:00:00
21 2017-10-01 00:00:00
22 2017-11-01 00:00:00
23 2017-12-01 00:00:00
24 2018-01-01 00:00:00
25 2018-02-01 00:00:00
26 2018-03-01 00:00:00
我现在的代码如下:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
df['login_month'] = pd.to_datetime(df['login_month'])
ax = (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
# ax.xaxis.set_major_locator(mdates.YearLocator())
# ax.xaxis.set_minor_locator(mdates.MonthLocator())
# ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
# ax.xaxis.set_minor_formatter(mdates.DateFormatter('%b'))
# # round to nearest years.
# datemin = np.datetime64(df['login_month'][0], 'M')
# datemax = np.datetime64(df['login_month'][1294], 'M') + np.timedelta64(1, 'Y')
# area_plot.set_xlim(xmin=datemin, xmax=datemax)
plt.yticks(np.arange(0, 12000000, 250000))
plt.grid(True)
它缺少刻度线中的月份和年份
@baccandr 当我尝试重现您的结果时,出现以下错误:
AttributeError module 'matplotlib.dates' has no attribute 'ConciseDateFormatter' ---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-66-49dd880fcf13> in <module>
14
15 locator = mdates.AutoDateLocator(minticks=15, maxticks=30)
---> 16 formatter = mdates.ConciseDateFormatter(locator)
17 axs.xaxis.set_major_locator(locator)
18 axs.xaxis.set_major_formatter(formatter)
AttributeError: module 'matplotlib.dates' has no attribute 'ConciseDateFormatter'
【问题讨论】:
-
看起来您的示例代码几乎是complete,但您没有展示如何将数据加载到
df。如果你能证明这一点,人们会更容易提供帮助。 -
@DonKirkby 注意到了!下次也会加入有代表性的数据集
标签: python matplotlib charts visualization