File with sequence of numbers to two column array/list and then plot

120 Views Asked by At

I have a text file (test.txt) which just has some sequence of numbers e.g. 2, 5, 6, 9, 3, 1, 3, 5, 5, 6, 7, 8, etc. My main goal is to plot odd placed numbers on the X-axis and even placed numbers on the Y-axis. To do that i thought, perhaps i can first store them in a list/array with two columns and then just plot the first column vs the second. How can I do this in python?

1

There are 1 best solutions below

0
Niklas Mertsch On

I am assuming your data to be saved in myFile.csv like this:

2, 5, 6, 9, 3, 1, 3, 5, 5, 6, 7, 8
5, 6, 9, 3, 1, 3, 5, 5, 6, 7, 8, 8

you can load it into a numpy array with np.loadtxt. If you don't want your dataset to be divided into multiple lines, you can flatten it.

import numpy as np
from matplotlib import pyplot as plt

# load data
data = np.loadtxt('myFile.csv', dtype=int, delimiter=', ')
data = data.flatten() # if data was saved in multiple lines

You can split your data using list comprehensions.

# process data
x = [data[i] for i in range(len(data)) if i%2 == 0]
y = [data[i] for i in range(len(data)) if i%2 == 1]

And then plot it.

# plot data
plt.plot(x, y, '.') # '.' only shows dots, no connected lines
plt.show()