-1

Suppose I have this huge set of data in a .txt file that has the following structure: first and the second column represents a discrete bidimensional domain, and the third column represents the values calculated on each point of the discrete X and Y axis. Example given below

x  y  z
-1 -1 100
-1 0 50
-1 1 100
0 -1 50
0 0 0
0 1 50
1 -1 100
0 -1 50
1 1 100

It seems stupid, but I've been struggling to turn this data into vectors and matrices like X = [-1, 0, 1], Y = [-1, 0, 1] and Z = [[100, 50, 100], [50, 0, 50], [100, 50, 100]]. I went through many technics and methods using numpy, but coudn't manage to make it!

As a bonus: would turning this data into vectors and matrices, like I described, be a good way to plot it in a 3dscatter ou 3dcountour type using matplotlib?

1 Answers1

0

To plot a scatter plot, you will not need to do anything with your data. Just plot the there columns as they are.

To get the values you want in you question, you can take the unique elements of the x and y column and reshape the z column according to those dimensions.

u="""x  y  z
-1 -1 100
-1 0 50
-1 1 100
0 -1 50
0 0 0
0 1 50
1 -1 100
1 0 50
1 1 100"""

import io
import numpy as np

data = np.loadtxt(io.StringIO(u), skiprows=1)

x = np.unique(data[:,0])
y = np.unique(data[:,1])
Z = data[:,2].reshape(len(x), len(y))

print(Z)

prints

[[100.  50. 100.]
 [ 50.   0.  50.]
 [100.  50. 100.]]

Differing y coordinates are now along the second axis of the array, which is rather unusual for plotting with matplotlib.

Hence, to get the values gridded for plotting with contour, you will need to do the same reshaping to all three columns and transpose (.T) them.

import matplotlib.pyplot as plt

X = data[:,0].reshape(len(x), len(y)).T
Y = data[:,1].reshape(len(x), len(y)).T
Z = data[:,2].reshape(len(x), len(y)).T

plt.contour(X,Y,Z)
plt.show()

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712