5

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?

11
  • 1
    Show the values data['x'] and data['y']. Are they right? Commented May 7, 2015 at 3:09
  • If I type print data['x'] and print data['y'], it shows [ 0. 0.1 0.2 0.3 0.5 1. 0. 0.1 0.2 0.3 0.5 1. ] and [ 1. 2. 3. 4. 7. 9. 6. 10. 11. 12. 13. 14.] Commented May 7, 2015 at 3:12
  • 1
    No commas? What's type(data['x'])? Commented May 7, 2015 at 3:13
  • @user42298 The above output doesn't look like output from a repr() of a list. Are you sure this is the output? Are you parsing the input values as floats? Commented May 7, 2015 at 3:14
  • 2
    Oh. Your x-values aren't in order, so the plot is going back to x=0 at the 6th point. Does that explain it? Commented May 7, 2015 at 3:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.