来自csv文件的Python条形图

时间:2018-04-02 17:23:32

标签: python csv plot

我有一个csv文件如下:

Statistic,Evap_a_lm,Evap_am,Evap_lm,Evap_od
STD_ctessel:,0.553843,0.572184,0.546684,0.568511
STD_htessel:,0.761471,0.938552,0.747172,0.919918
Mean_Bias_ctessel:,-0.290104,-0.248983,-0.310019,-0.267554
Mean_Bias_htessel:,-0.214769,-0.0868161,-0.233181,-0.103245

从这个CSV文件中我想迭代索引和行名称组件以生成条形图,如下所示:enter image description here

为此,我确实生成了以下代码:

import os,sys,math,time
import csv
from matplotlib import rc
from matplotlib import pyplot as plt
from matplotlib import patches as mpatches
import numpy as np
import pandas as pd
variables = ["Evap"]
names = ["od", "lm", "am", "a_lm"]
models = ["ctessel", "htessel"]
statistics = ['STD']
for variable in variables:
    for name in names:
        data = pd.read_csv("merged.txt", delimiter='\t')
        data.set_index('Statistic')
        for stat in statistics:
            for model in models:
                od = data.loc[[stat + "_" + model + ":"],[variable + "_od"]].astype(float)
                lm = data.loc[[stat + "_" + model + ":"],[variable + "_lm"]].astype(float)
                am = data.loc[[stat + "_" + model + ":"],[variable + "_am" + station]].astype(float)
                a_lm = data.loc[[stat + "_" + model + ":"],[variable + "_a_lm" + station]].astype(float)
                plt.title(variable + " " + stat, y=1.02)
                r1 = [1]
                r2 = [2]
                r3 = [3]
                r4 = [4]
                plt.bar(r1, od, width = barWidth, color="green", label='Original input')
                plt.bar(r2, lm, width = barWidth, color="yellow", label='Modis LAI')
                plt.bar(r3, am, width = barWidth, color="red", label='Modis Albedo')
                plt.bar(r4, a_lm, width = barWidth, color="blue", label='Modis LAI')
plt.savefig(outdir + station + "_" + "perf.pdf")

但不幸的是它不起作用,我总是有错误消息,显然它无法将标题的字符串转换为float:

ValueError: could not convert string to float: 'Evap_od'

有谁知道解决方法?

1 个答案:

答案 0 :(得分:1)

这应解决您的大部分问题。使用pandas可以避免所有额外的代码。然后,您可以从此处根据需要对其进行格式化。

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('merged.txt')
df = df.set_index('Statistic')


fig, ax = plt.subplots()

df.plot(kind='bar', ax=ax)

ax.grid(color='gray', linestyle='-', alpha=0.3)

Example Plot