0

I have a data file (x and y columns) with different data separated by two empty lines. Is there a way to plot n blocks separately in the same figure using Python?

1 1
2 2
3 3

4 5
5 6
6 7

This is the code I have tried:

import matplotlib.pyplot as plt from scipy
import * import numpy as np

data=np.loadtxt('data.dat')
i=0
for i in len(data):
    plt.plot(data[i:i+3,0], data[i:i+3], 'ro')
    i=i+4,
return

But I seem to be getting a wrong plot. What am I missing?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • using [matplotlib](http://matplotlib.org/) would be my first guess when it comes to plot something. – SMFSW Mar 24 '17 at 16:44
  • how are organized your data ? it come from a .txt file ? have you tried anything ? – Dadep Mar 24 '17 at 17:17
  • Yes it is, but if you want any help you will have to include the code you have attempted so far, or at least show us where you are stuck!? – AP. Mar 24 '17 at 17:38

1 Answers1

0

If you're trying to put all of the data on the same plot, then just ignore the blank lines:

with open('data.dat') as f:
    lines = [line for line in f if line.strip()]

data = [line.split() for line in lines]
plt.plot(*zip(*data), marker='o', color='r', ls='')
plt.show()

Otherwise, if you're trying to iterate over each block then you could split the data on the \n\n whitespace:

with open('data.dat') as f:
    lines = f.read()

blocks = lines.split('\n\n')
for block in blocks:
    data = [line.split() for line in block.splitlines()]
    plt.plot(*zip(*data), marker='o', color='r', ls='')
    plt.show()
Community
  • 1
  • 1
brennan
  • 3,392
  • 24
  • 42