简体   繁体   English

使用matplotlib在python代码for-loop中将折线图转换为条形图

[英]Turn line chart into bar plot in python code for-loop with matplotlib

I have a script that takes multiple .csv files and outputs multiple line plots. 我有一个脚本,需要多个.csv文件并输出多个折线图。 I would like for these plots to be bar charts since they're showing rainfall. 我希望这些图成为条形图,因为它们显示降雨。 But I haven't been able to get plot.bar.() to work. 但是我无法使plot.bar.()工作。 This is the code that works for me so far but it's not correct. 到目前为止,这是对我有用的代码,但这是不正确的。 Any help? 有什么帮助吗?

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']

    final[['date','rf']].plot()
    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))

在此处输入图片说明

This is an extension of my previous question: Automate making multiple plots in python using several .csv files 这是我先前问题的扩展: 使用多个.csv文件在python中自动制作多个图

Use DataFrame.plot.bar : 使用DataFrame.plot.bar

final[['date','rf']].plot.bar()

Or DataFrame.plot : DataFrame.plot

final[['date','rf']].plot(kind='bar')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM