0

I have a file "data.dat" following data:

[[0.2 0.3 0.4][0.3 0.2 0.4][0.5 0.3 0.4]]

Now I am reading this data from file as

f=open("data.dat","r")
z=f.read()
f.close()

I have x=[1 2 3] & y=[1 2 3]. I made a meshgrid from x & y as

X,Y=plt.meshgrid(x,y)

Now I am trying to do contour plot using

plt.contourf(X,Y,Z)

But it is showing error as: ValueError: could not convert string to float: [[0.2 0.3 0.4][0.3 0.2 0.4][0.5 0.3 0.4]]

Any suggestion about how to read Z array as float from file or to write the "data.dat" file in other way?

1 Answers1

0

You are reading a string from the file and putting that string to Z. But in fact you need two-dimensional array of floats instead of string. So you have to parse your string. It can be done by converting it to JSON like this:

import json
with open("data.dat") as f:
    z = f.read()
z = z.replace(' ', ', ').replace('][', '], [')
Z = json.loads(z)

the other (and better) way is to use JSON to store your data in a file.

import json    
Z = [[0.2, 0.3, 0.4], [0.3, 0.2, 0.4], [0.5, 0.3, 0.4]]
with open("data.dat", 'w') as f:
    json.dump(Z, f)

You also can try different formats, like CSV.

Ilya V. Schurov
  • 7,687
  • 2
  • 40
  • 78
  • @IIyaV The thing is I am generating data using a C++ code. It is about a cosmological simulation. However, I imported, exported and then imported data as you told me, but the same error is coming again. But I was able to solve the problem by reshaping data output taking hints from here: http://stackoverflow.com/questions/6323737/make-a-2d-pixel-plot-with-matplotlib – DeusExMachina Feb 12 '17 at 06:05