2

I have been using gnuplot for as long as I remember. Recently i have been wanting to switch to matplotlib.

One basic function of gnuplot i frequently use is the 'index' function.

Suppose I have the following data file (foo.dat):

1 1
2 2
3 3


1 1
2 4
3 9

I could do:

plot 'foo.dat' index 0 u 1:2
replot 'foo.dat' index 1 u 1:2

to get two lines corresponding to the two data sets in the same plot. How would one import such a file using numpy and plot it using matplotlib?

Here is how I would like my final plot to look like: enter image description here

1

1 Answer 1

3

Use genfromtxt to read in the file:

import numpy as np
import matplotlib.pyplot as plt

a = np.genfromtxt('foo.dat')

gives:

array([[ 1.,  1.],
       [ 2.,  2.],
       [ 3.,  3.],
       [ 1.,  1.],
       [ 2.,  4.],
       [ 3.,  9.]])

Then plot:

plt.plot(a[3:,0],a[3:,1],marker='x',color='g')
plt.plot(a[0:3,0],a[0:3,1],marker='x',color='r')

gives: enter image description here

EDIT

Following @Cristoph's comment

To read in automatically, you could split the file into chunks, if you read in with pandas. But you'd need to write a script to find the rows to skip for a large file.

import pandas as pd
b=pd.read_csv('foo.dat',sep=' ',chunksize=3,header=None,skiprows=(3,4),index_col=0)
for c in b:
    plt.plot(c)

Note the skiprows parameter - you'd need to create a list to fit your file if it's longer.

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

4 Comments

This is not exactly what I want. I have edited my question to add a figure of what i want.
The important point is, that gnuplot uses the two empty lines to automatically recognize different blocks, which can then be accessed with index.
That's not automatic, you must still give concrete numbers. You cannot say: plot the first two blocks, no matter how many points each contains, which is what gnuplot does...
@Christoph In that case the long answer to gforce89's comment is "yes, but you need to write a script to find the spaces between blocks."

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.