0

I have data file say data.txt as,

1 10 
2 20
3 30
4 41
5 49

1 11
2 19
3 32
4 37
5 52

Note there are two set of data. I want to plot them in same graph. In gnuplot it is very simple we just have to run plot 'data.txt' with line and we will get a graph like this, enter image description here

Actually I have 50 such set in the same data file. I have just started learning python. I want to plot this data file using numpy and matplotlib.

There are similar threads in this forum like,

How to plot data from multiple two column text files with legends in Matplotlib?

How can you plot data from a .txt file using matplotlib?

but I could not find anything similar to my issue.

George
  • 5,808
  • 15
  • 83
  • 160
ddas
  • 199
  • 1
  • 15

1 Answers1

0

One idea can be to read the complete file, split it at the positions where a double line break occurs, .split('\n\n') and read in each part using numpy.loadtxt.

import numpy as np
from io import StringIO 
import matplotlib.pyplot as plt

filename="data.txt"
with open(filename) as f:
    data = f.read()

data = data.split('\n\n')

for d in data:
    ds = np.loadtxt(StringIO(unicode(d)))
    plt.plot(ds[:,0],ds[:,1])

plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • 1
    `unicode` gave a NameError while running with `python3` because `Python 3` renamed the `unicode` type to `str`. After replacing it with `str` it worked, thanks for your help. – ddas Oct 10 '17 at 18:02