13

I have a .dat file that contains two columns of numbers so it looks something like this:

111    112
110.9  109
103    103

and so on.

I want to plot the two columns against one another. I have never dealt with a .dat file before so I am not sure where to start.

So far I figured out that numpy has something I can use to call.

data = numpy.loadtxt('data.DAT')

but I'm not sure where to go from here. Any ideas?

4
  • 1
    so then you have a 2d array of points ... this has nothing to do with *.dat file could be anything *.txt would work exactly the same... your real question is "How Do I plot a numpy array?" Commented Sep 7, 2012 at 4:35
  • 1
    It's easy in gnuplot ;^). plot 'yourfile.dat' u 1:2 (but of course, that doesn't address the actual question ...) Commented Sep 7, 2012 at 4:35
  • You can use Scavis that interfaces NumPy (or JNumeric in Java) as explained in the Scavis manual Commented Jan 29, 2014 at 3:36
  • Possible duplicate of Matplotlib basic plotting from text file Commented Aug 29, 2016 at 18:55

2 Answers 2

15

Numpy doesn't support plotting by itself. You usually would use matplotlib for plotting numpy arrays.

If you just want to "look into the file", I think the easiest way would be to use plotfile.

import matplotlib.pyplot as plt 

plt.plotfile('data.dat', delimiter=' ', cols=(0, 1), 
             names=('col1', 'col2'), marker='o')
plt.show()

You can use this function almost like gnuplot from within ipython:

$ ipython --pylab
...
...
In [1]: plt.plotfile('data.dat', delimiter=' ', cols=(0, 1), 
...                  names=('col1', 'col2'), marker='o')

or put it in a shell script and pass the arguments to it to use it directly from your shell

plotfile_example

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. This definitely does the job!
4
import numpy as np
import matplotlib.pyplot as plot
#data = np.loadtxt("plot_me.dat")
#x,y=np.loadtxt("plot_me.dat",unpack=True) #thanks warren!
#x,y =  zip(*data)
#plot.plot(x, y, linewidth=2.0)
plot.plot(*np.loadtxt("plot_me.dat",unpack=True), linewidth=2.0)
plot.show()

[Edit]Thanks for the tip i think its as compact as possible now :P

plot 1

If you want it to be log10 just call log10 on the nparray)

plot.plot(*np.log10(np.loadtxt("plot_me.dat",unpack=True)), linewidth=2.0)

log10

3 Comments

You can make the code even more concise by using the unpack keyword in loadtxt: x, y = np.loadtxt('plot_me.dat', unpack=True)
Thanks a lot! Do you know how I could take the log_10 of these columns?
I think just plot.plot(*np.log10(np.loadtxt("plot_me.dat",unpack=True)), linewidth=2.0)

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.