5

I wish to make a Histogram in Matplotlib from an input file containing the raw data (.txt). I am facing issues in referring to the input file. I guess it should be a rather small program. Any Matplotlib gurus, any help ?

I am not asking for the code, some inputs should put me on the right way !

2 Answers 2

9

i would recommend using 'loadtxt' which is actually in the NumPy library. There are related functions in Matplotlib (csv2rec) but Matplotlib is actually standardizing on loadtxt.

Here's how it works:

from matplotlib import pyplot as PLT

with open('name_of_your_file.csv') as f:
  v = NP.loadtxt(f, delimiter=",", dtype='float', comments="#", skiprows=1, usecols=None)

'v', the object returned from 'loadtxt', is an n x m NumPy array.

'loadtxt' accepts either a file or a file descriptor. The instance above has most of the method signature. 'skiprows' is an integer that specifies the number of rows counting from the top that you want to skip; it's common to set it to "1" to skip the header row; 'usecols' begins at '0' and is a list reciting the columns you want to include ('None' is the default, and means 'include all'). The other parameters work as expected.

To plot a histogram from this data:

from matplotlib import pyplot as PLT

v_hist = NP.ravel(v)   # 'flatten' v
fig = PLT.figure()
ax1 = fig.add_subplot(111)

n, bins, patches = ax1.hist(v_hist, bins=50, normed=1, facecolor='green')
PLT.show()
Sign up to request clarification or add additional context in comments.

2 Comments

you should always use genfromtxt instead of loadtxt, especially when dealing with large files, as it has the same default behaviour but can be 20 times as fast.
Make sure you also put in a statement to import numpy. For the code above to work, one would need to have import numpy as NP for everything to work. Great answer!
0

You can't directly tell matplotlib to make a histogram from an input file - you'll need to open the file yourself and get the data from it. How you'd do that depends on the format of the file - if it's just a file with a number on each line, you can just go through each line, strip() spaces and newlines, and use float() to convert it to a number.

2 Comments

@Daniel G: Did that, but it gets rather messy !
@Arkapravo - True, and I hadn't realized about doug's solution - use that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.