Surface Plot of 3D Arrays using matplotlib - python
I have a function of the form f(x,y,z) and want to create a surface plot for it (level sets) using matplotlib. The problem I have is that plot_surface only accepts 3 arguments, whereas the type of plot I want to do is create a grid of x,y,z values and then plot the value of my function f at each of those points.
Here is a minimal example:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
bounds = [1,1,1]
numpoints = 25
x = np.linspace(-bounds[0], bounds[0], numpoints)
y = np.linspace(-bounds[1], bounds[1], numpoints)
z = np.linspace(-bounds[2], bounds[2], numpoints)
X, Y, Z = np.meshgrid(x, y, z)
s = X.shape
Ze = np.zeros(s)
Zp = np.zeros(s)
DT = np.zeros((numpoints**3,3))
# convert mesh into point vector for which the model can be evaluated
c = 0
for i in range(s[0]):
for j in range(s[1]):
for k in range(s[2]):
DT[c,0] = X[i,j,k]
DT[c,1] = Y[i,j,k]
DT[c,2] = Z[i,j,k]
c = c+1;
# this could be any function that returns a shape (numpoints**3,)
Ep = np.square(DT)[:,0]
c = 0
for i in range(s[0]):
for j in range(s[1]):
for k in range(s[2]):
Zp[i,j,k] = Ep[c]
c = c+1;
Now I would like to plot Zp as level sets in matplotlib. Is this possible?
The only way to represent 4 variables (x, y, x, f(x, y, z)) I could think in matplotlib is scatter the grid of x, y, z and give a color to the points that is proportional to f(x, y, z):
bounds = [1,1,1]
numpoints = 11
x = np.linspace(-bounds[0], bounds[0], numpoints)
y = np.linspace(-bounds[1], bounds[1], numpoints)
z = np.linspace(-bounds[2], bounds[2], numpoints)
X, Y, Z = np.meshgrid(x, y, z)
For exaple let's say taht f(x,y,z)=sin(x+y)+cos(y+z):
f_xyz = np.sin(X+Y)+np.cos(Y+Z)
Now let's scatter:
plt.figure(figsize=(7,7))
ax = plt.subplot(projection="3d")
ax.scatter(X, Y, Z, s=10, alpha=.5, c=f_xyz, cmap="RdBu")
plt.show()
As you can see the result is a bit confusing and not very clear, but it strongly depends on what function you want to plot. I hope you could find a better way
Related
3D plot using delauney triangulation using four 1dimensional arrays. First three determine the coordinates while fourth determines the color
I am trying to achieve a plot like the one shown bellow: The code I am using is the following: import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import matplotlib.tri as tri from matplotlib.colors import Normalize # Example usage x = np.linspace(0, 10, 500) f1 = lambda x: x**2 f2 = lambda x: 3*x**1.4 f3 = lambda x: 2*x**1.2 f4 = lambda x: 2*x**1 X = f1(x) Y = f2(x) Z = f3(x) Z1 = f4(x) # Find the indices of the non-nan values valid_indices = np.logical_not(np.logical_or(np.isnan(X), np.logical_or(np.isnan(Y), np.isnan(Z)))) # Use the non-nan indices to index into the arrays x = X[valid_indices] y = Y[valid_indices] z = Z[valid_indices] z1 = Z1[valid_indices] # Create grid values first. ngridx = 300 ngridy = 300 xi = np.linspace(x.min(), x.max(), ngridx) yi = np.linspace(y.min(), y.max(), ngridy) # Perform linear interpolation of the data (x,y) # on a grid defined by (xi,yi) triang = tri.Triangulation(x, y) interpolator_z = tri.LinearTriInterpolator(triang, z) interpolator_z1 = tri.LinearTriInterpolator(triang, z1) Xi, Yi = np.meshgrid(xi, yi) zi = interpolator_z(Xi, Yi) z1i = interpolator_z1(Xi, Yi) X, Y, Z, Z1 = xi, yi, zi, z1i fig = plt.gcf() ax1 = fig.add_subplot(111, projection='3d') minn, maxx = z1.min(), z1.max() norm = Normalize() surf = ax1.plot_surface(X,Y,Z, rstride=1, cstride=1, facecolors=cm.jet(norm(Z1)), vmin=minn, vmax=maxx, shade=False) #surf =ax.plot_trisurf(X,Y,Z, triangles=tri.triangles, cmap=plt.cm.Spectral) m = cm.ScalarMappable(cmap=cm.jet) m.set_array(Z1) The result I am getting is close but not quite what I want: I am looking to get something that looks closer to this: Any ideas on how I could improve my result?
3D graphing the complex values of a function in Python
This is the real function I am looking to represent in 3D: y = f(x) = x^2 + 1 The complex function would be as follows: w = f(z) = z^2 + 1 Where z = x + iy and w = u + iv. These are four dimentions (x, y, u, v), but one can use u for 3D graphing. We get: f(x + iy) = x^2 + 2xyi - y^2 + 1 So: u = x^2 - y^2 + 1 and v = 2xy This u is what is being used in the code below. import numpy as np import matplotlib.pyplot as plt x = np.linspace(-100, 101, 150) y = np.linspace(-100, 101, 150) X, Y = np.meshgrid(x,y) U = (X**2) - (Y**2) + 1 fig = plt.figure(dpi = 300) ax = plt.axes(projection='3d') ax.plot_surface(X, Y, Z) plt.show() The following images are the side-view of the 3D function and the 2D plot for reference. I do not think they are alike. Likewise, here is the comparison between the 3 side-view and the 2D plot of w = z^3 + 1. They seem to differ as well. I have not been able to find too many resources regarding plotting in 3D using complex numbers. Because of this and the possible discrepancies mentioned before, I think the code must be flawed, but I can't figure out why. I would be grateful if you could correct me or advise me on any changes. The inspiration came from Welch Labs' 'Imaginary Numbers are Real' YouTube series where he shows a jaw-dropping representation of the complex values of the function I have been tinkering with. I was just wondering if anybody could point out any flaws in my reasoning or the execution of my idea since this code would be helpful in explaining the importance of complex numbers to HS students. Thank you very much for your time.
The f(z) = z^2 + 1 projection (that is, side-view) looks OK to me. You can use this technique to add the projections; this code: import numpy as np import matplotlib.pyplot as plt from matplotlib import cm def f(z): return z**2 + 1 def freal(x, y): return x**2 - y**2 + 1 x = np.linspace(-100, 101, 150) y = np.linspace(-100, 101, 150) yproj = 0 # value of y for which to project xu axes xproj = 0 # value of x to project onto yu axes X, Y = np.meshgrid(x,y) Z = X + 1j * Y W = f(Z) U = W.real fig = plt.figure() ax = plt.axes(projection='3d') ## surface ax.plot_surface(X, Y, U, alpha=0.7) # xu projection xuproj = freal(x, yproj) ax.plot(x, xuproj, zs=101, zdir='y', color='red', lw=5) ax.plot(x, xuproj, zs=yproj, zdir='y', color='red', lw=5) # yu projection yuproj = freal(xproj, y) ax.plot(y, yuproj, zs=101, zdir='x', color='green', lw=5) ax.plot(y, yuproj, zs=xproj, zdir='x', color='green', lw=5) # partially reproduce https://www.youtube.com/watch?v=T647CGsuOVU&t=107s x = np.linspace(-3, 3, 150) y = np.linspace(0, 3, 150) X, Y = np.meshgrid(x,y) U = f(X + 1j*Y).real fig = plt.figure() ax = plt.axes(projection='3d') ## surface ax.plot_surface(X, Y, U, cmap=cm.jet) ax.set_box_aspect( (np.diff(ax.get_xlim())[0], np.diff(ax.get_ylim())[0], np.diff(ax.get_zlim())[0])) #ax.set_aspect('equal') plt.show() gives this result: and The axis ticks don't look very good: you can investigate plt.xticks or ax.set_xticks (and yticks, zticks) to fix this. There is a way to visualize complex functions using colour as a fourth dimension; see complex-analysis.com for examples.
3D plot in python plot (X, Y, Z, data)
This python code allows to plot Z = f(X,Y). My question is what should I modify to plot f(X,Y,Z,data)? Let's say that data corresponds to temperature, and I have temperature for each location X, Y, and Z. import numpy as np import matplotlib.pyplot as pet from mpl_toolkits.mplot3d import Axes3D x = np.arange(0,25,1) y = np.arange(0,25,1) x,y = np.meshgrid(x,y) z = x**2 + y**2 fig = plt.figure() axes = fig.gca(projection='3d') axes.plot_surface(x,y,z) plt.show() I guess that I need to have x = np.arange(0,25,1) y = np.arange(0,25,1) z = np.arange(0,25,1) x,y,z = np.meshgrid(x,y,z) but axes.plot_surface(x,y,z) will not be working anymore. What I should use instead?
Plot 4th dimension with Python
I would to know if there is the possibility to plot in four dimensions using python. In particular I would to have a tridimensional mesh X, Y, Z and f(X,Y,Z) = 1 or f(X,Y,Z) = 0. So I need to a symbol (for example "o" or "x") for some specific point (X,Y,Z). I don't need to a color scale. Note that I have 100 matrices (512*512) composed by 1 or 0: so my mesh should be 512*512*100. I hope I have been clear! Thanks. EDIT: This is my code: X = np.arange(W.shape[2]) Y = np.arange(W.shape[1]) Z = np.arange(W.shape[0]) X, Y, Z = np.meshgrid(X, Y, Z) fig = plt.figure() ax = fig.gca(projection='3d') for z in range(W.shape[0]): indexes = np.where(W[z]) ax.scatter(X[indexes], Y[indexes], ???, marker='.') ax.set_xlabel('X = columns') ax.set_ylabel('Y = rows') ax.set_zlabel('Z') plt.show() W is my tridimensional matrix, so: W[0], W[1], etc are 512x512 matrices. My question is: what have I to write insted of ??? in my code. I know I shouldn't ask this, but I can't understand the idea.
You could create inspect the value of f(x,y,z) for layers of z to see if they are non-zero or not, and then scatterplot the function based on this. e.g. for nz layers of (n,n) matrices, each a slice of a sphere: import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt n, nz = 48, 24 x, y = np.linspace(-n//2,n//2-1,n), np.linspace(-n//2,n//2-1,n) X, Y = np.meshgrid(x, y) def f(x,y,z): return (X**2 + Y**2 + (z-nz//2)**2) < (n*0.2)**2 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for z in range(nz): layer = f(X, Y, z) indexes = np.where(layer) ax.scatter(X[indexes], Y[indexes], layer[indexes]*(z-nz//2), marker='.') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show() For random non-zero elements of f(x,y,z): import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt n, nz = 12, 10 x, y, z = np.linspace(0,n-1,n), np.linspace(0,n-1,n), np.linspace(0,nz-1,nz) X, Y, Z = np.meshgrid(x, y, z) f = np.random.randint(2, size=(n,n,nz)) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for z in range(nz): indexes = np.where(f[...,z]) ax.scatter(X[indexes], Y[indexes], f[indexes]+z, marker='.') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') plt.show() But with your large arrays, you may run into problems (a) with memory and the speed of the plotting and (b) being able to resolve detail in the "central" block of the plot.
How do you create a 3D surface plot with missing values matplotlib?
I am trying to create a 3D surface energy diagram where an x,y position on a grid contains an associated z level. The issue is that the grid is not uniform (ie, there is not a z component for every x,y position). Is there a way to refrain from plotting those values by calling them NaN in the corresponding position in the array? Here is what I have tried so far: import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D import pylab from matplotlib import cm #Z levels energ = np.array([0,3.5,1,-0.3,-1.5,-2,-3.4,-4.8]) #function for getting x,y associated z values? def fun(x,y,array): return array[x] #arrays for grid x = np.arange(0,7,0.5) y = np.arange(0,7,0.5) #create grid X, Y = np.meshgrid(x,y) zs = np.array([fun(x,y,energ) for x in zip(np.ravel(X))]) Z = zs.reshape(X.shape) plt3d = plt.figure().gca(projection='3d') #gradients now with respect to x and y, but ideally with respect to z only Gx, Gz = np.gradient(X * Y) G = (Gx ** 2 + Gz ** 2) ** .5 # gradient magnitude N = G / G.max() # normalize 0..1 plt3d.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=cm.jet(N), edgecolor='k', linewidth=0, antialiased=False, shade=False) plt.show() I cannot post image here of this plot but if you run the code you will see it But I would like to not plot certain x,y pairs, so the figure should triangle downward to the minimum. Can this be accomplished by using nan values? Also would like spacing between each level, to be connected by lines. n = np.NAN #energ represents the z levels, so the overall figure should look like a triangle. energ = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,2.6,n,2.97,n,2.6,n,2.97,n,2.6,n,3.58,n],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,n,1.09,n,1.23,n,1.09,n,1.23,n,1.7,n,n],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,n,n,-0.65,n,-0.28,n,-0.65,n,0.33,n,n,n],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,n,n,n,-2.16,n,-2.02,n,-1.55,n,n,n,n],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,n,n,n,n,-3.9,n,-2.92,n,n,n,n,n,],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,n,n,n,n,n,-4.8,n,n,n,n,n,n,]]) plt3d = plt.figure().gca(projection='3d') Gx, Gz = np.gradient(X * energ) # gradients with respect to x and z G = (Gx ** 2 + Gz ** 2) ** .5 # gradient magnitude N = G / G.max() # normalize 0..1 x = np.arange(0,13,1) y = np.arange(0,13,1) X, Y = np.meshgrid(x,y) #but the shapes don't seem to match up plt3d.plot_surface(X, Y, energ, rstride=1, cstride=1, facecolors=cm.jet(N), edgecolor='k', linewidth=0, antialiased=False, shade=False ) Using masked arrays generates the following error: local Python[7155] : void CGPathCloseSubpath(CGMutablePathRef): no current point. n = np.NAN energ = np.array([[0,0,0,0,0,0,0,0,0,0,0,0,0],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,2.6,n,2.97,n,2.6,n,2.97,n,2.6,n,3.58,n],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,n,1.09,n,1.23,n,1.09,n,1.23,n,1.7,n,n],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,n,n,-0.65,n,-0.28,n,-0.65,n,0.33,n,n,n],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,n,n,n,-2.16,n,-2.02,n,-1.55,n,n,n,n],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,n,n,n,n,-3.9,n,-2.92,n,n,n,n,n,],[n,n,n,n,n,n,n,n,n,n,n,n,n],[n,n,n,n,n,n,-4.8,n,n,n,n,n,n,]]) x = np.arange(0,13,1) y = np.arange(0,13,1) X, Y = np.meshgrid(x,y) #create masked arrays mX = ma.masked_array(X, mask=[[0,0,0,0,0,0,0,0,0,0,0,0,0],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,0,1,0,1,0,1,0,1,0,1,0,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,0,1,0,1,0,1,0,1,0,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,0,1,0,1,0,1,0,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,0,1,0,1,0,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,0,1,0,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,0,1,1,1,1,1,1]]) mY = ma.masked_array(Y, mask=[[0,0,0,0,0,0,0,0,0,0,0,0,0],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,0,1,0,1,0,1,0,1,0,1,0,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,0,1,0,1,0,1,0,1,0,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,0,1,0,1,0,1,0,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,0,1,0,1,0,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,0,1,0,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,0,1,1,1,1,1,1]]) m_energ = ma.masked_array(energ, mask=[[0,0,0,0,0,0,0,0,0,0,0,0,0],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,0,1,0,1,0,1,0,1,0,1,0,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,0,1,0,1,0,1,0,1,0,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,0,1,0,1,0,1,0,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,0,1,0,1,0,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,0,1,0,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,0,1,1,1,1,1,1]]) plt3d = plt.figure().gca(projection='3d') plt3d.plot_surface(mX, mY, m_energ, rstride=1, cstride=1, edgecolor='k', linewidth=0, antialiased=False, shade=False) plt.show()
I was playing around with the code from this forum post, and I was able to make the graph have missing values. You can try the code yourself! I got it to work using float("nan") for the missing values. import plotly.graph_objects as go import numpy as np x = np.arange(0.1,1.1,0.1) y = np.linspace(-np.pi,np.pi,10) #print(x) #print(y) X,Y = np.meshgrid(x,y) #print(X) #print(Y) result = [] for i,j in zip(X,Y): result.append(np.log(i)+np.sin(j)) result[0][0] = float("nan") upper_bound = np.array(result)+1 lower_bound = np.array(result)-1 fig = go.Figure(data=[ go.Surface(z=result), go.Surface(z=upper_bound, showscale=False, opacity=0.3,colorscale='purp'), go.Surface(z=lower_bound, showscale=False, opacity=0.3,colorscale='purp')]) fig.show()