2017-02-24 14 views
1

複数の.csvファイルを取り、複数の棒グラフを出力するスクリプトがあります。データは毎日降水量の合計であるため、x軸は昼間の形式の日付である%d %m %Yです。つまり、コードは365日すべてをラベルに含めるように試みますが、x軸は詰まってしまいます。 1月に1つのラベルのみを「Jan 01」という形式で含めるために使用できるコードは何ですか。matplotlibを使用してPython棒グラフでdatetimeデータのx軸目盛りラベルの頻度を変更します

import pandas as pd 
import time 
import os 
import matplotlib.pyplot as plt 

files = ['w.pod.csv', 
't.pod.csv', 
'r.pod.csv', 
'n.pod.csv', 
'm.pod.csv', 
'k.pod.csv', 
'j.pod.csv', 
'h.pod.csv', 
'g.pod.csv', 
'c.pod.csv', 
'b.pod.csv'] 

for f in files: 
    fn = f.split('.')[0] 
    dat = pd.read_csv(f) 
    df0 = dat.loc[:, ['TimeStamp', 'RF']] 
    # Change time format 
    df0["time"] = pd.to_datetime(df0["TimeStamp"]) 
    df0["day"] = df0['time'].map(lambda x: x.day) 
    df0["month"] = df0['time'].map(lambda x: x.month) 
    df0["year"] = df0['time'].map(lambda x: x.year) 
    df0.to_csv('{}_1.csv'.format(fn), na_rep="0") # write to csv 

    # Combine for daily rainfall 
    df1 = pd.read_csv('{}_1.csv'.format(fn), encoding='latin-1', 
       usecols=['day', 'month', 'year', 'RF', 'TimeStamp']) 
    df2 = df1.groupby(['day', 'month', 'year'], as_index=False).sum() 
    df2.to_csv('{}_2.csv'.format(fn), na_rep="0", header=None) # write to csv 

    # parse date 
    df3 = pd.read_csv('{}_2.csv'.format(fn), header=None, index_col='datetime', 
      parse_dates={'datetime': [1,2,3]}, 
      date_parser=lambda x: pd.datetime.strptime(x, '%d %m %Y')) 

    def dt_parse(date_string): 
     dt = pd.datetime.strptime(date_string, '%d %m %Y') 
     return dt 

    # sort datetime 
    df4 = df3.sort() 
    final = df4.reset_index() 

    # rename columns 
    final.columns = ['date', 'bleh', 'rf'] 

    [![enter image description here][1]][1] final[['date','rf']].plot(kind='bar') 
    plt.suptitle('{} Rainfall 2015-2016'.format(fn), fontsize=20) 
    plt.xlabel('Date', fontsize=18) 
    plt.ylabel('Rain/mm', fontsize=16) 
    plt.savefig('{}.png'.format(fn)) 

これは私の前の質問の拡張である:Automate making multiple plots in python using several .csv files

enter image description here

答えて

1

それは簡単ではありませんが、これは動作します:

#sample df with dates of one year, rf are random integers 
np.random.seed(100) 
N = 365 
start = pd.to_datetime('2015-02-24') 
rng = pd.date_range(start, periods=N) 

final = pd.DataFrame({'date': rng, 'rf': np.random.randint(50, size=N)}) 
print (final.head()) 
     date rf 
0 2015-02-24 8 
1 2015-02-25 24 
2 2015-02-26 3 
3 2015-02-27 39 
4 2015-02-28 23 

fn = 'suptitle' 
#rot - ratation of labels in axis x 
ax = final.plot(x='date', y='rf', kind='bar', rot='45') 
plt.suptitle('{} Rainfall 2015-2016'.format(fn), fontsize=20) 
plt.xlabel('Date', fontsize=18) 
plt.ylabel('Rain/mm', fontsize=16) 
#set cusom format of dates 
ticklabels = final.date.dt.strftime('%Y-%m-%d') 
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels)) 

#show only each 30th label, another are not visible 
spacing = 30 
visible = ax.xaxis.get_ticklabels()[::spacing] 
for label in ax.xaxis.get_ticklabels(): 
    if label not in visible: 
     label.set_visible(False) 

plt.show() 

graph

+0

それはほとんど動作します!私はちょうど 'Traceback(最も最近のコール最後): ファイル"の行1のエラーメッセージを取得します。 NameError:名前 'ticker 'は' ax.xaxis.set_major_formatter(ticker.FixedFormatter (ティックラベル)) '。このためにパッケージをインポートする必要はありますか? @jezrael – JAG2024

+0

最初に 'import matplotlib.ticker as ticker'だけ必要です。 – jezrael

+0

ありがとうございます!それはうまくいった。 – JAG2024

関連する問題