環境
Python 3.6.8
pandas 0.24.1
実現したいこと
Python Pandas で crosstab を使いクロス集計したデータをグラフ表示した場合、日付ラベルを月単位にしたいです。
今回のサンプルではデータ数が少ないため問題ありませが、データ数が増えると日付ラベルが多すぎて日付が見えなくなってしまうため。月単位、もしくはもっと間隔を開けたいです。
サンプルデータ
tera.csv
csv
1日時,グループ,ユーザー 22019/06/07 09:37:11,ほにゃ部,太郎 32019/06/07 09:37:50,らら部,花子 42019/06/07 10:52:02,ほげ部,一郎 52019/06/07 14:40:34,らら部,花子 62019/06/07 17:07:56,ほげ部,二郎 72019/06/18 09:34:52,らら部,桃子 82019/06/18 10:48:39,ほげ部,一郎 92019/06/18 10:48:40,ほにゃ部,次郎 102019/06/18 19:16:25,ほげ部,一郎 112019/07/09 08:47:47,らら部,花子 122019/07/09 08:58:13,ほげ部,一郎 132019/07/09 09:29:06,ほにゃ部,次郎 142019/07/09 09:59:46,らら部,花子 152019/08/12 08:28:09,ほげ部,二郎 162019/08/12 08:28:14,ほにゃ部,次郎 172019/08/12 09:50:17,ほげ部,一郎 182019/08/12 10:02:07,らら部,花子 192019/09/13 09:13:09,ほげ部,一郎 202019/09/13 09:30:54,ほげ部,二郎 212019/09/13 09:58:32,らら部,花子 222019/09/13 10:04:44,らら部,桃子 232019/09/13 10:06:13,らら部,花子 242019/09/13 10:52:41,らら部,桃子 252019/09/13 11:06:59,ほげ部,一郎 262019/09/14 06:18:13,ほげ部,二郎 272019/09/14 06:18:35,ほにゃ部,次郎 282019/10/14 06:19:29,ほげ部,二郎 292019/11/14 12:43:31,らら部,花子 302019/11/15 09:30:00,らら部,桃子
# 現在のサンプルソース
python
1import pandas as pd 2import matplotlib.pyplot as plt 3 4df = pd.read_csv('tera1.csv', usecols=['日時','グループ','ユーザー']) 5df['日付'] = df['日時'].str.split(n=0, expand=True)[0] 6 7xt = pd.crosstab(df['日付'],df['グループ']) 8 9ax = xt.plot(kind='bar') 10plt.show()
サンプルの実行結果
](3ef17316999f0cc521f690fa484e4139.png)
試したこと
python
1import numpy as np 2import matplotlib.pyplot as plt 3import matplotlib.dates as mdates 4import matplotlib.cbook as cbook 5 6years = mdates.YearLocator() # every year 7months = mdates.MonthLocator() # every month 8years_fmt = mdates.DateFormatter('%Y') 9 10# Load a numpy structured array from yahoo csv data with fields date, open, 11# close, volume, adj_close from the mpl-data/example directory. This array 12# stores the date as an np.datetime64 with a day unit ('D') in the 'date' 13# column. 14with cbook.get_sample_data('goog.npz') as datafile: 15 data = np.load(datafile)['price_data'] 16 17fig, ax = plt.subplots() 18ax.plot('date', 'adj_close', data=data) 19 20# format the ticks 21ax.xaxis.set_major_locator(years) 22ax.xaxis.set_major_formatter(years_fmt) 23ax.xaxis.set_minor_locator(months) 24 25# round to nearest years. 26datemin = np.datetime64(data['date'][0], 'Y') 27datemax = np.datetime64(data['date'][-1], 'Y') + np.timedelta64(1, 'Y') 28ax.set_xlim(datemin, datemax) 29 30# format the coords message box 31ax.format_xdata = mdates.DateFormatter('%Y-%m-%d') 32ax.format_ydata = lambda x: '$%1.2f' % x # format the price. 33ax.grid(True) 34 35# rotates and right aligns the x labels, and moves the bottom of the 36# axes up to make room for them 37fig.autofmt_xdate() 38 39plt.show()
参照: Matplotlib Documentation - Date tick Label
こちらのソースを参考にしたりしてみたのですが、crosstab からだと Axes が返ってくるため、figure をどう取得したらいいのかわからず、autofmt_xdate()ができないのでよく分かりませんでした。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/30 13:15
2019/05/31 07:28
2019/05/31 07:28
2019/05/31 07:30
2019/05/31 20:43