-5

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?

COMA FIL
  • 1
  • 1
  • Show us what you tried, it will be easier to help. But yes, you need to take the data from the file, sort even and odd number then plot it – AdriBento Mar 28 '18 at 12:17
  • I have been trying to use this answer https://stackoverflow.com/questions/13545388/plot-data-from-csv-file-with-matplotlib# but I am fairly new to python and trying to make sense of the code. – COMA FIL Mar 28 '18 at 13:48

1 Answers1

0

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()
Niklas Mertsch
  • 1,399
  • 12
  • 24