Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting data from CSV files using matplotlib

My csv file looks

0.0 1
0.1 2
0.2 3
0.3 4
0.5 7
1.0 9


0.0 6
0.1 10
0.2 11
0.3 12
0.5 13
1.0 14

...

and I want to draw the first column in x axis, second column as y axis. So my code is

import matplotlib.pyplot as plt
from numpy import genfromtxt
data=genfromtxt("test",names=['x','y'])
ax=plt.subplot(111)
ax.plot(data['x'],data['y'])
plt.show()

But this connect the end point of graph, showing straight line, graph
(source: tistory.com)

What I want is this graph. graph
(source: tistory.com)

Then how do I read data file or are there any options in matplotlib disconnecting the line?

like image 680
user42298 Avatar asked Nov 09 '22 14:11

user42298


1 Answers

As others mentioned in the comments, every call to plot will plot all the point-pairs it gets so you should slice the data for every column. If all the lines are of size 6 points you can do something like this:

import matplotlib.pyplot as plt
from numpy import genfromtxt
data=genfromtxt("test",names=['x','y'])
x=data['x']
y=data['y']
columnsize = int(len(x)/6)
ax=plt.subplot(111)
for i in range(columnsize):
    ax.plot(x[i*6:(i+1)*6],y[i*6:(i+1)*6])
plt.show()

this code works when x and y are of type numpy.ndarray. numpy arrays support indexing and slicing as python standard syntax.

like image 159
Amen Avatar answered Nov 14 '22 23:11

Amen