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.

1
  • Can you show the code that you have? Commented Oct 10, 2017 at 9:37

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

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.

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.