python 2d contourf plot using 3d np array data - python

I have a problem here.
My data is a 3d shape of np array
(256, 256, 1) = (x coordinate, y coordinate, pressure value)
Now I would like to draw a contour plot using this np array.
But the problem is that the shape of my data does not fit into plt.contourf
Any idea on how to preprocess my data before feeding it to contourf?

Since you have a singular value for each position [M,N], you can simply squeeze out that dimension and have it represented by a matrix of shape [M,N].
data = data.squeeze(2)
plt.contourf(data)
The squeezed and original array contain the exact same data, but are just represented slightly differently.

Related

Python 3D Vector Field Plot from 4D numpy array

I was wondering whether it is possible to create a 3D vector Field PLot from a 4D numpy array.
The array is in the shape (10,10,10,3) which is basically the three vector components at each respective grid point. Grid spacing is 1.
There is a matplotlib function ax.quiver() (https://matplotlib.org/stable/gallery/mplot3d/quiver3d.html) that I would like to use. It can be used for irregular grid, which is why it takes 6 meshgrids as input (x,y,z,u,v,w) for the grid and the vector components respectively.
I know how to create the xyz meshgrids, but I am not sure how to extract the vector components uvw from my 4d array.
Help would be appreciated!

Is it possible to do interpolation over 4d data?

I am trying to implement this paper. I have to try to interpolate the latent code of an autoencoder, as mentioned in the paper. The latent code is the encoded input of an autoencoder. The shape of the latent code (for two samples) is (2, 64, 64, 128).
This is what I have done:
image1 = sel_train_encodings[0]
image2 = sel_train_encodings[1]
x = image1[:,0,0]
x_new = image2[:,0,0]
new_array = interp1d(x, image1, axis=0, fill_value='extrapolate', kind='linear')(x_new)
I basically took the encodings of two images and tried to interpolate( with extrapolation for some points as all points don't lie in the same range) and then did interpolation over one of the axes. But the results I later obtain with these interpolated values are not so good, am I doing something wrong/how else to do it?
According to one of the given answers, I also tried to do 2D interpolation in the following way:
image1 = sel_train_encodings[0]
image2 = sel_train_encodings[1]
new_array = griddata((x,z),y,(x_new, z_new), method='cubic', fill_value='extrapolate')
But this resulted in the error:
ValueError: shape mismatch: objects cannot be broadcast to a single shape
Scipy has a couple of 2D interpolation routines, depending on the spacing of the (x, y):
If your data is on a regular grid, try scipy.interpolate.RectBivariateSpline(). This is probably most applicable to images.
If your data is collected on a grid with uneven rectangular intervals, you want to use scipy.interpolate.interp2d().
If all bets are off and the (x, y) are scattered without any clear grid, try scipy.interpolate.griddata()

Python: Convert 2d point cloud to grayscale image

I have an array of variable length filled with 2d coordinate points (coming from a point cloud) which are distributed around (0,0) and i want to convert them into a 2d matrix (=grayscale image).
# have
array = [(1.0,1.1),(0.0,0.0),...]
# want
matrix = [[0,100,...],[255,255,...],...]
how would i achieve this using python and numpy
Looks like matplotlib.pyplot.hist2d is what you are looking for.
It basically bins your data into 2-dimensional bins (with a size of your choice).
here the documentation and a working example is given below.
import numpy as np
import matplotlib.pyplot as plt
data = [np.random.randn(1000), np.random.randn(1000)]
plt.scatter(data[0], data[1])
Then you can call hist2d on your data, for instance like this
plt.hist2d(data[0], data[1], bins=20)
note that the arguments of hist2d are two 1-dimensional arrays, so you will have to do a bit of reshaping of our data prior to feed it to hist2d.
Quick solution using only numpy without the need for matplotlib and therefor plots:
import numpy as np
# given a 2dArray "array" and a desired image shape "[x,y]"
matrix = np.histogram2d(array[:,0], array[:,1], bins=[x,y])

Converting an array with values in log scale to a regular array

I am trying to plot a histogram of elements of a downloaded .py file. The array had a shape (200, 3649, 13). So I had reshaped it to a 2D array by preforming the function
samples = chain[:,-2000:,:].reshape((-1,13))
I hence plotted the histogram by doing
plt.hist(samples[:,3])
The graph gave me values in log scale, but I need to plot it in a linear scale. How do I proceed?

scipy ND Interpolating over NaNs

I have been trouble working out how to use the scipy.interpolate functions (either LinearNDInterpolator, griddata or Preferably NearestNDInterpolator)
There are some tutorials online but i am confused what form my data needs to be in.
The online documentation for nearestND is terrible.
The function asks for:
x : (Npoints, Ndims) ndarray of floats
Data point coordinates.
y : (Npoints,) ndarray of float or complex
Data point values.
I have data in the form: lat,long,data,time held within an xarray dataset. There are some gaps in the data I would like to fill in.
I don't understand how to tell the function my x points.
i have tried (lat,long) as a tuple and np.meshgrid(lat,long) but can't seem to get it going.
Any help on how i can pass my lat,long coordinates into the function? Bonus points for time coordinates as well to make the estimates more robust through the third dimension.
Thanks!
i have tried (lat,long) as a tuple
If lat and long are 1D arrays or lists, try this:
points = np.array((lat, long)).T # make a 2D array of shape Npoints x 2
nd = NearestNDInterpolator(points, data)
The you can compute interpolated values as nd(lat1, long1), etc.
Scipy provides multivariate interpolation methods for both unstructured data and data point regularly placed on a grid. Unstructured data means the data could be provided as a list of non-ordered points. It seems that your data is structured: it is an array of size (480, 2040). However, the NearestNDInterpolator works on unstructured data. The flatten method can be used to transform the array to a list (1d) of value (of length 480*2040). The same have to be done for the coordinates. meshgrid is used to have the coordinates for every points of the grid, and again flatten is used to obtain a "list" of 2d coordinates (an array of shape 480*2040 x 2).
Here is an example which go from structured data to unstructured:
import numpy as np
lat = np.linspace(2, 6, 10)
lon = np.linspace(5, 9, 14)
latM, lonM = np.meshgrid(lat, lon) # M is for Matrix
dataM = np.sin(latM)*np.cos(lonM) # example of data, Matrix form
from scipy.interpolate import NearestNDInterpolator
points = np.array((latM.flatten(), lonM.flatten())).T
print( points.shape )
# >>> (140, 2)
f_nearest = NearestNDInterpolator(points, dataM.flatten())
f_nearest(5, 5)
Working with NaNs should not be a big problem in this case, because it is just a missing point in the list, except that the coordinates of the missing points have to be removed from the list too.

Categories