Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot a histogram without the zero values in python?

When I try to make a histogram without the zero values, I get an error:

Traceback (most recent call last):.

I have a list of Beam_irradiance_DNI values which include several zeroes. I can make histogram, but I don't want the zero values.

import matplotlib.pyplot as plt
import numpy as np

import csv

# Reading data from csv file
with open('Upington_DNI.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
Hour_of_year = []
Beam_irradiance = []
for row in readCSV:
    hour = row[0]
    DNI = row[1]
    Hour_of_year.append(hour)
    Beam_irradiance.append(DNI)
Hours_since00hrsJan1 = [float(Hour_of_year[c]) for c in       range(1,len(Hour_of_year))]
Beam_irradiance_DNI=[float(Beam_irradiance[c]) for c in range(1,len(Beam_irradiance))]

plt.figure(3)
Beam_irradiance_DNI[ Beam_irradiance_DNI==0 ] = np.nan
plt.hist(Beam_irradiance_DNI, color="grey")
plt.title("Histogram for Beam irradiance - DNI")
plt.xlabel("Beam irradiance - DNI [W/m2]"); plt.ylabel("Probability of  occurrence")
plt.show()

I dont know what is wrong here.

like image 702
Arvind Sastry Avatar asked Mar 11 '16 23:03

Arvind Sastry


2 Answers

You can only perform logical indexing (data[data != 0]) on a numpy.array not a normal python list. If you want to remove values from a python list, you'll want to use a list comprehension to do that.

newvalues = [x for x in Beam_irradiance_DNI if x != 0]

The other alternative is to actually convert your python list to a numpy array.

nparray = np.array(Bean_irradiance_DNI)

Then you will be able to do the logical indexing you want to perform

nparray[nparray == 0] = np.nan

The other alternative is to not alter the array itself, and simply pass only the non-zero values to hist

plt.hist(Beam_irradiance_DNI[Beam_irradiance_DNI != 0], color="grey")

If you're still having issues with zeros, it's likely due to the fact that these numbers are stored as floating point numbers and their value isn't exactly zero. For this you would want to use the following condition to detect "zeros".

is_zero = np.absolute(Beam_irradiance_DNI) < np.finfo(float).eps
Beam_irradiance_DNI[is_zero] = np.nan
like image 116
Suever Avatar answered Oct 20 '22 01:10

Suever


import numpy as np
Beam_irradiance_DNI = np.array(Beam_irradiance_DNI)
plt.hist(Beam_irradiance_DNI[Beam_irradiance_DNI>0], color="grey")

this should work because you only keep the elements which are above zero (Beam_irradiance_DNI>0 is a boolean mask used as index). In case you want to use this further save it as a variable but if you only want to exclude zeros for the histogram don't bother with redefining your variable.

like image 36
MSeifert Avatar answered Oct 19 '22 23:10

MSeifert