2017-08-07 8 views
0

パンダでデータフレームの2つの列をプロットするとき、どのように日付形式を変更できますか?例えばパンダでデータフレームの2つの列を互いにプロットするときの日付形式を変更

は、私が実行した場合:

import pandas as pd 
import numpy as np 
from matplotlib import pyplot as plt 

np.random.seed(1) 
dates = pd.date_range('1/1/2000', periods=50) 
print('dates: {0}'.format(dates)) 
df = pd.DataFrame(np.random.randn(len(dates), 1), index=dates, columns=['A']) 

print('df: {0}'.format(df)) 
plt.figure(figsize=(60,15)) 
df.plot(y='A', use_index=True) 
plt.xticks(rotation=70) 
plt.savefig('plot.png', dpi=300, bbox_inches='tight') 

は私が取得:

enter image description here

にはどうすればxticksに表示される日付の形式を制御することができますか?

以下のように、日付を文字列にキャストする必要がありますか、それとも解決策がありますか?

import pandas as pd 
import numpy as np 
from matplotlib import pyplot as plt 

np.random.seed(1) 
dates = pd.date_range('1/1/2000', periods=50) 
print('dates: {0}'.format(dates)) 
# I have just changed the line below to introduce `.astype(str)`: 
df = pd.DataFrame(np.random.randn(len(dates), 1), index=dates.astype(str), columns=['A']) 

print('df: {0}'.format(df)) 
plt.figure(figsize=(60,15)) 
df.plot(y='A', use_index=True) 
plt.xticks(rotation=70) 
plt.savefig('plot2.png', dpi=300, bbox_inches='tight') 

enter image description here

答えて

1

あなたはmatplotlib.datesからDayLocatorMonthLocatorオブジェクトを使用することができます。私は毎月の最初の大きな目盛りを設定し、毎月11日と21日の小目盛りを設定し、日付をYYYY-MM-DDと設定しました。

import matplotlib.pyplot as plt 
from matplotlib.dates import DayLocator, MonthLocator, DateFormatter 

fig, ax = plt.subplots(1,1) 
ax.plot(df) 
ax.xaxis.set_major_locator(MonthLocator()) 
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) 
ax.xaxis.set_minor_locator(DayLocator([11,21])) 
ax.xaxis.set_minor_formatter(DateFormatter('%Y-%m-%d')) 
plt.setp(ax.xaxis.get_ticklabels(which='both'), rotation=70) 
fig.tight_layout() 
plt.show() 

enter image description here

関連する問題