Reputation: 531
I have a csv file as follow:
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
From this CSV file I would like to iterate through indexes and rows names components in order to produce barplots, like this one:
For that I did produce the following code:
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")
But unfortunately it is not working and I always have the error message that, obviously it cannot convert the string of the header to float:
ValueError: could not convert string to float: 'Evap_od'
Does anyone knows a workaround?
Upvotes: 0
Views: 2937
Reputation: 1016
This should fix most of your issues. Using pandas you can avoid all the extra code. You can then format it as you like from here.
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)
Upvotes: 1