更改 matplotlib 中日期时间轴的格式
Changing the formatting of a datetime axis in matplotlib
我有一个索引为 datetime
的系列,我想绘制它。我想在 y 轴上绘制系列的值,在 x 轴上绘制系列的索引。 Series
如下所示:
2014-01-01 7
2014-02-01 8
2014-03-01 9
2014-04-01 8
...
我使用 plt.plot(series.index, series.values)
生成图表。但图表看起来像:
问题是我只想知道年份和月份(yyyy-mm 或 2016 年 3 月)。但是,图表包含小时、分钟和秒。我怎样才能删除它们以获得我想要的格式?
您可以尝试这样的操作:
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
df = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M'))
fig,ax1 = plt.subplots()
plt.plot(df.index,df.values)
monthyearFmt = mdates.DateFormatter('%Y %B')
ax1.xaxis.set_major_formatter(monthyearFmt)
_ = plt.xticks(rotation=90)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# sample data
N = 30
drange = pd.date_range("2014-01", periods=N, freq="MS")
np.random.seed(365) # for a reproducible example of values
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)
fig, ax = plt.subplots()
ax.plot(df.index, df.values)
ax.set_xticks(df.index)
# use formatters to specify major and minor ticks
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
_ = plt.xticks(rotation=90)
你应该看看 matplotlib 的这个原生函数:
fig.autofmt_xdate()
查看源网站上的例子Custom tick formatter
我有一个索引为 datetime
的系列,我想绘制它。我想在 y 轴上绘制系列的值,在 x 轴上绘制系列的索引。 Series
如下所示:
2014-01-01 7
2014-02-01 8
2014-03-01 9
2014-04-01 8
...
我使用 plt.plot(series.index, series.values)
生成图表。但图表看起来像:
问题是我只想知道年份和月份(yyyy-mm 或 2016 年 3 月)。但是,图表包含小时、分钟和秒。我怎样才能删除它们以获得我想要的格式?
您可以尝试这样的操作:
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
df = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M'))
fig,ax1 = plt.subplots()
plt.plot(df.index,df.values)
monthyearFmt = mdates.DateFormatter('%Y %B')
ax1.xaxis.set_major_formatter(monthyearFmt)
_ = plt.xticks(rotation=90)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# sample data
N = 30
drange = pd.date_range("2014-01", periods=N, freq="MS")
np.random.seed(365) # for a reproducible example of values
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)
fig, ax = plt.subplots()
ax.plot(df.index, df.values)
ax.set_xticks(df.index)
# use formatters to specify major and minor ticks
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
_ = plt.xticks(rotation=90)
你应该看看 matplotlib 的这个原生函数:
fig.autofmt_xdate()
查看源网站上的例子Custom tick formatter