Jagte
Jagte

Reputation: 533

how to use python/matplotlib to plot data with blank line inbetween

I have a single data file that looks like this

#X    Y 
1     23.2 
2     24.01
3     67.34
4     68.90
# 

1    7.87 
2    6.90  
3    5.78   
4    7.89 

Note the gap between the lines. In my plot I should have two separate lines just as gnuplot would plot it. How to do this with python/matplotlib. I am currently getting one line that joins back.

Here is how I am plotting currently:

F=loadtxt('fort.30',comments='#',dtype='float64' )
t=F[:,0]
E=F[:,1]  
plt.plot(t,E) 

Thanks for the comments and response

Upvotes: 2

Views: 3880

Answers (3)

tobias_k
tobias_k

Reputation: 82949

You could split your F array into several subplots whenever the value in the first column is smaller than it was in the line before.

breaks = [i for i in range(len(F)) if i > 0 and F[i, 0] < F[i-1, 0]]
borders = [0] + breaks + [len(F)]
subplots = [F[borders[i]:borders[i+1]] for i in range(len(borders)-1)]

Now, you can plot the individual subplots.

for f in subplots:
    t, E = f[:, 0], f[:, 1]
    plt.plot(t, E)
plt.show()

Of course, that's only if the first value of a new subplot will always be lower than the last one of the previous subplot. If you have to rely on the # to subdivide the plots, you will probably have to parse the file yourself.

Upvotes: 1

Dr. Jan-Philip Gehrcke
Dr. Jan-Philip Gehrcke

Reputation: 35826

You have not shown any code so far. Your current code might help, based on this people might come up with a working solution for you.

Basically, you have to do the file processing in Python yourself. If # is the delimiter between your datasets, then write yourself a function in Python that is reading a file, interpreting line by line. If a line contains 2 numbers separated by whitespace, add the data of that line to the current data set. If a line contains only a # (number sign), then start a new data set.

After doing so, you have a clear representation of your data sets (either in Python lists or in numpy arrays) and can worry about plotting those.

Upvotes: 0

segasai
segasai

Reputation: 8548

Add None's or nans between the parts of your dataset:

plt.plot([1,2,None,3,4],[1,0,None,2,1])

Upvotes: 3

Related Questions