【问题标题】:Turn line chart into bar plot in python code for-loop with matplotlib使用matplotlib将折线图转换为python代码for循环中的条形图
【发布时间】:2017-07-15 11:40:17
【问题描述】:

我有一个脚本,它需要多个 .csv 文件并输出多个线图。我希望这些图是条形图,因为它们显示的是降雨量。但我无法让plot.bar.() 工作。这是到目前为止对我有用的代码,但它不正确。有什么帮助吗?

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))

这是我之前问题的延伸:Automate making multiple plots in python using several .csv files

【问题讨论】:

    标签: python pandas matplotlib plot ggplot2


    【解决方案1】:

    使用DataFrame.plot.bar:

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

    DataFrame.plot:

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

    【讨论】:

    • 这很简单!谢谢!!您还知道更改 xtick 标签的代码吗?现在它正在尝试放置所有 365 个日期,但轴被堵塞了。如果每 30 个刻度(天)被标记一次就好了。
    • 谢谢!请查看我的另一个问题:stackoverflow.com/questions/42444020/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多