web-dev-qa-db-ja.com

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)を使用してグラフを生成します。しかし、グラフは次のようになります。

graph

問題は、年と月だけを持ちたいということです。ただし、グラフには時間、分、秒が含まれます。希望の書式を取得するために、それらを削除するにはどうすればよいですか?

11
Sheryl
# sample data
import numpy as np
import pandas as pd

N = 30
drange = pd.date_range("2014-01", periods=N, freq="MS")
values = {'values':np.random.randint(1,20,size=N)}
df = pd.DataFrame(values, index=drange)

# use formatters to specify major and minor ticks
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots()
ax.plot(df.index, df.values)
ax.set_xticks(df.index)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))
ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m"))
_=plt.xticks(rotation=90)    

time series plot

15
andrew_reece

次のようなものを試すことができます:

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)

enter image description here

13
Scott Boston