x 轴刻度线未出现在图表中
x-axis tick marks not appearing in graph
我试图让月份和年份以 'Mon YYYY' 格式显示在 x 轴上,但到目前为止我只能让年份显示出来。
我试过使用
的变体
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'
和下图
编辑:
如果你还在 运行 matplotlib 2.2.x 你可以使用 matplotlib ticker api:
import matplotlib.ticker as ticker
#generate some random data
idx= pd.date_range(start='2016-01-01', end='2020-02-01',freq='m')
df=pd.DataFrame({'rand1':np.random.random(len(idx)),
'rand2': np.random.random(len(idx)),
'rand3': np.random.random(len(idx))},index=idx)
#stack plot
fig, axs = plt.subplots(figsize=(20,18),constrained_layout=True)
axs.stackplot(df.index,df.rand1,df.rand2,df.rand3)
#Adjust ticks
axs.set_xticks(pd.to_datetime(idx.year.unique().astype(str)), minor=False)
axs.xaxis.set_major_formatter(ticker.FixedFormatter(idx.year.unique().astype(str)))
#create bimonthly minor ticks
months=pd.date_range(start=idx[0], end=idx[-1],freq='2M')
axs.set_xticks(pd.to_datetime(months), minor=True)
axs.xaxis.set_minor_formatter(ticker.FixedFormatter(months.month.astype(str)))
#adjust major ticks aesthetics
axs.tick_params(axis='x',which='major',length=5,width=1.5, pad=4, labelsize=14)
如果你想显示 less/more 个月你可以简单地调整 pd.date_range(start=idx[0], end=idx[-1],freq='2M')
中的频率。
这是结果:
对于 matplotlib 3.1.x:
我可能会使用 matplotlib auto date locator together with the concise date formatter:
#generate some random data
idx= pd.date_range(start='2016-01-01', end='2020-01-01',freq='m')
df=pd.DataFrame({'rand1':np.random.random(len(idx)),
'rand2': np.random.random(len(idx)),
'rand3': np.random.random(len(idx))},index=idx)
#stack plot
fig, axs = plt.subplots(figsize=(20,18),constrained_layout=True)
axs.stackplot(df.index,df.rand1,df.rand2,df.rand3)
locator = mdates.AutoDateLocator(minticks=15, maxticks=20)
formatter = mdates.ConciseDateFormatter(locator)
axs.xaxis.set_major_locator(locator)
axs.xaxis.set_major_formatter(formatter)
通过更改自动定位器的参数,您可以调整刻度的频率。 Here 您还可以找到一些关于如何更改简洁日期格式化程序的输出的示例。
p.s.
我使用了 matplotlib stackplot 函数,但您也应该能够使用 pandas plot.area 函数获得类似的结果。
p.p.s
对于您的示例,我无法重现您的问题,因为日期跨度太短,并且来自 pandas 的自动格式化程序工作正常。
这是我得到的结果:
我试图让月份和年份以 'Mon YYYY' 格式显示在 x 轴上,但到目前为止我只能让年份显示出来。
我试过使用
的变体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'
和下图
编辑: 如果你还在 运行 matplotlib 2.2.x 你可以使用 matplotlib ticker api:
import matplotlib.ticker as ticker
#generate some random data
idx= pd.date_range(start='2016-01-01', end='2020-02-01',freq='m')
df=pd.DataFrame({'rand1':np.random.random(len(idx)),
'rand2': np.random.random(len(idx)),
'rand3': np.random.random(len(idx))},index=idx)
#stack plot
fig, axs = plt.subplots(figsize=(20,18),constrained_layout=True)
axs.stackplot(df.index,df.rand1,df.rand2,df.rand3)
#Adjust ticks
axs.set_xticks(pd.to_datetime(idx.year.unique().astype(str)), minor=False)
axs.xaxis.set_major_formatter(ticker.FixedFormatter(idx.year.unique().astype(str)))
#create bimonthly minor ticks
months=pd.date_range(start=idx[0], end=idx[-1],freq='2M')
axs.set_xticks(pd.to_datetime(months), minor=True)
axs.xaxis.set_minor_formatter(ticker.FixedFormatter(months.month.astype(str)))
#adjust major ticks aesthetics
axs.tick_params(axis='x',which='major',length=5,width=1.5, pad=4, labelsize=14)
如果你想显示 less/more 个月你可以简单地调整 pd.date_range(start=idx[0], end=idx[-1],freq='2M')
中的频率。
这是结果:
对于 matplotlib 3.1.x:
我可能会使用 matplotlib auto date locator together with the concise date formatter:
#generate some random data
idx= pd.date_range(start='2016-01-01', end='2020-01-01',freq='m')
df=pd.DataFrame({'rand1':np.random.random(len(idx)),
'rand2': np.random.random(len(idx)),
'rand3': np.random.random(len(idx))},index=idx)
#stack plot
fig, axs = plt.subplots(figsize=(20,18),constrained_layout=True)
axs.stackplot(df.index,df.rand1,df.rand2,df.rand3)
locator = mdates.AutoDateLocator(minticks=15, maxticks=20)
formatter = mdates.ConciseDateFormatter(locator)
axs.xaxis.set_major_locator(locator)
axs.xaxis.set_major_formatter(formatter)
通过更改自动定位器的参数,您可以调整刻度的频率。 Here 您还可以找到一些关于如何更改简洁日期格式化程序的输出的示例。
p.s. 我使用了 matplotlib stackplot 函数,但您也应该能够使用 pandas plot.area 函数获得类似的结果。
p.p.s 对于您的示例,我无法重现您的问题,因为日期跨度太短,并且来自 pandas 的自动格式化程序工作正常。
这是我得到的结果: