Saad.Akhtar312 Saad.Akhtar312 - 5 months ago 29
Python Question

Looping over list of vectors to create histograms for each vector

I am working on creating histograms for output data from a CFD simulation.

Since output variables are a lot more than one, I want to loop over the list containing output variables and create separate figure for each histogram of output variable.

Here is a sample code of my working thus far:

import numpy as np
import matplotlib.pyplot as plt
import os

# set default directory and import data

path="C:/Users/Pacman/Data files"
os.chdir(path)
data =np.genfromtxt('MCS_10000cases_Sc_B.txt')

#Create output vectors

Power=data[:,][:,9]
Per_Lk=data[:,][:,10]
VFR_Fan=data[:,][:,11]
VFR_MF=data[:,][:,13]
TP=data[:,][:,14]

#Plotting histgram

numbins=40
var=['Power','Per_Lk','VFR_Fan','VFR_MF','TP']

for i in var:
plt.hist(i,numbins,color='g')
plt.figure()
plt.show()


When I run the code shown above it gives me a long error which ends with the following statement:


TypeError: len() of unsized object


When I try to plot histograms one by one without the loop it works fine. I've tried looking up the error and implement some fixes but it didn't help.

Any ideas for the fixes will be highly appreciated.

Answer

Give this code a try:

var = {'Power': data[:,][:,9],
       'Per_Lk': data[:,][:,10],
       'VFR_Fan': data[:,][:,11],
       'VFR_MF': data[:,][:,13],
       'TP': =data[:,][:,14],
       }
numbins = 40

for i in var:
    plt.hist(var[i], numbins, color='g')
    plt.figure()
    plt.show()