Thomas Luckie
Thomas Luckie

Reputation: 31

Properly reading/plotting data separated by '>'

I have data formatted as follows:

87.2224   -0.0453
87.1561   -0.1580
>
90.8429   -0.1164
90.3849   -0.1020
90.2667   -0.1246
>
87.1002   -0.0553
87.1561   -0.1580
>

Where the columns are x,y coordinates of a line and each > separates a new line.

How can I properly read this using numpy (or some other Python library) and plot it using matplotlib so that three separate lines can be plotted?

Alternatively, is there something I could do to format the data prior to reading it in Python to make this easier?

Thank you! :)

Upvotes: 1

Views: 49

Answers (3)

Thomas Luckie
Thomas Luckie

Reputation: 31

@pdrersin gave me enough to figure this out:

x=[]
y=[]
with open("data.txt") as file:

    for line in file:
        if ">" not in line:
            coords = line.split()
            x.append(float(coords[0]))
            y.append(float(coords[1]))
        if ">" in line:
            plt.plot(x,y)
            x=[]
            y=[]

This plots each line individually without connecting their ends.

Upvotes: 1

Sheldore
Sheldore

Reputation: 39052

You can simply use np.loadtxt to read in your data by specifying > as a comment. This will ignore these lines. You can later reshape these arrays into bits/chunks of two to plot individual lines.

import numpy as np

x, y = np.loadtxt('filename.txt', unpack=True, comments='>')

# (array([87.2224, 87.1561, 90.3849, 90.2667, 87.1002, 87.1561]),
#  array([-0.0453, -0.158 , -0.102 , -0.1246, -0.0553, -0.158 ]))

Upvotes: 1

pdrersin
pdrersin

Reputation: 311

The below should do it:

x=[]
y=[]
with open("data.txt") as file:

    for line in file:
         if ">" not in line:
              coords = line.split()
              # print(coords)
              x.append(float(coords[0]))
              y.append(float(coords[1]))

Upvotes: 1

Related Questions