[Tutor] Reading in large .dat file

Peter Otten __peter__ at web.de
Wed Jun 29 15:21:14 EDT 2016


Colin Ross wrote:

> On Wed, Jun 29, 2016 at 2:41 PM, Peter Otten <__peter__ at web.de> wrote:
> 
>> Colin Ross wrote:
>>
>> > Good afternoon,
>> >
>> > I have a .dat file that is 214 rows by 65 columns that I would like to
>> > read into python and plot the 1st column versus all other columns.
>> >
>> > My code:
>> >
>> > 
#########################################################################
>> >
>> > import numpy as np
>> > import scipy
>> > import pylab as pl
>> > import matplotlib
>> > from matplotlib.ticker import ScalarFormatter, FormatStrFormatter
>> > import sys
>> >
>> > # Load in text from .dat file
>> >
>> > sed = np.loadtxt('spectra.dat', unpack = True)
>>
>> for flux in sed:
>>     pl.plot(wavelength, flux)
>>
>> > pl.xscale('log')
>> >
>> > pl.show()
>> >
>> > 
#########################################################################
>> >
>> > This is fine if I want to write out a separate line for each of the 65
>> > columns, but I would like to simplify the code by looping over the
>> > data. Can someone please help me formatting the loop correctly?
>>
> 
> Thank you for the fast response! I have tried this and it outputs the
> attached image. 

This is a text-only mailing list, so the image didn't make it through.

> It seems to only plot 1 curve, when I would have expected
> 64?

You probably got a traceback (error information on the commandline). It is 
always a good idea to include that. Example:

$ python3 flux2.py 
Traceback (most recent call last):
  File "flux2.py", line 15, in <module>
    pl.plot(wavelength,flux)
NameError: name 'wavelength' is not defined

The error indicates that there is no variable called wavelength. That's 
because I didn't note that you use the first column to define that, sorry.
Here's a modified script that should work:

import numpy as np
import pylab as pl

sed = np.loadtxt('spectra.dat', unpack=True)

wavelength = sed[0]
for flux in sed[1:]:
    pl.plot(wavelength, flux)                                                                                                                                                                                      
                                                                                                                                                                                                                   
pl.xscale('log')                                                                                                                                                                                                   
pl.show()                                                                                                                                                                                                          

The for loop now skips the first column.




More information about the Tutor mailing list