3D graphing the complex values of a function in Python - 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.
Related
Changing the linewidth and the color simultaneously in matplotlib
The figure above is a great artwork showing the wind speed, wind direction and temperature simultaneously. detailedly: The X axes represent the date The Y axes shows the wind direction(Southern, western, etc) The variant widths of the line were stand for the wind speed through timeseries The variant colors of the line were stand for the atmospheric temperature This simple figure visualized 3 different attribute without redundancy. So, I really want to reproduce similar plot in matplotlib. My attempt now ## Reference 1 http://stackoverflow.com/questions/19390895/matplotlib-plot-with-variable-line-width ## Reference 2 http://stackoverflow.com/questions/17240694/python-how-to-plot-one-line-in-different-colors def plot_colourline(x,y,c): c = plt.cm.jet((c-np.min(c))/(np.max(c)-np.min(c))) lwidths=1+x[:-1] ax = plt.gca() for i in np.arange(len(x)-1): ax.plot([x[i],x[i+1]], [y[i],y[i+1]], c=c[i],linewidth = lwidths[i])# = lwidths[i]) return x=np.linspace(0,4*math.pi,100) y=np.cos(x) lwidths=1+x[:-1] fig = plt.figure(1, figsize=(5,5)) ax = fig.add_subplot(111) plot_colourline(x,y,prop) ax.set_xlim(0,4*math.pi) ax.set_ylim(-1.1,1.1) Does someone has a more interested way to achieve this? Any advice would be appreciate!
Using as inspiration another question. One option would be to use fill_between. But perhaps not in the way it was intended. Instead of using it to create your line, use it to mask everything that is not the line. Under it you can have a pcolormesh or contourf (for example) to map color any way you want. Look, for instance, at this example: import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import interp1d def windline(x,y,deviation,color): y1 = y-deviation/2 y2 = y+deviation/2 tol = (y2.max()-y1.min())*0.05 X, Y = np.meshgrid(np.linspace(x.min(), x.max(), 100), np.linspace(y1.min()-tol, y2.max()+tol, 100)) Z = X.copy() for i in range(Z.shape[0]): Z[i,:] = c #plt.pcolormesh(X, Y, Z) plt.contourf(X, Y, Z, cmap='seismic') plt.fill_between(x, y2, y2=np.ones(x.shape)*(y2.max()+tol), color='w') plt.fill_between(x, np.ones(x.shape) * (y1.min() - tol), y2=y1, color='w') plt.xlim(x.min(), x.max()) plt.ylim(y1.min()-tol, y2.max()+tol) plt.show() x = np.arange(100) yo = np.random.randint(20, 60, 21) y = interp1d(np.arange(0, 101, 5), yo, kind='cubic')(x) dv = np.random.randint(2, 10, 21) d = interp1d(np.arange(0, 101, 5), dv, kind='cubic')(x) co = np.random.randint(20, 60, 21) c = interp1d(np.arange(0, 101, 5), co, kind='cubic')(x) windline(x, y, d, c) , which results in this: The function windline accepts as arguments numpy arrays with x, y , a deviation (like a thickness value per x value), and color array for color mapping. I think it can be greatly improved by messing around with other details but the principle, although not perfect, should be solid.
import numpy as np import matplotlib.pyplot as plt from matplotlib.collections import LineCollection x = np.linspace(0,4*np.pi,10000) # x data y = np.cos(x) # y data r = np.piecewise(x, [x < 2*np.pi, x >= 2*np.pi], [lambda x: 1-x/(2*np.pi), 0]) # red g = np.piecewise(x, [x < 2*np.pi, x >= 2*np.pi], [lambda x: x/(2*np.pi), lambda x: -x/(2*np.pi)+2]) # green b = np.piecewise(x, [x < 2*np.pi, x >= 2*np.pi], [0, lambda x: x/(2*np.pi)-1]) # blue a = np.ones(10000) # alpha w = x # width fig, ax = plt.subplots(2) ax[0].plot(x, r, color='r') ax[0].plot(x, g, color='g') ax[0].plot(x, b, color='b') # mysterious parts points = np.array([x, y]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) # mysterious parts rgba = list(zip(r,g,b,a)) lc = LineCollection(segments, linewidths=w, colors=rgba) ax[1].add_collection(lc) ax[1].set_xlim(0,4*np.pi) ax[1].set_ylim(-1.1,1.1) fig.show() I notice this is what I suffered.
Plotting a function of three variables in python
I would like to plot the contour lines for this function, however I cannot find any useful way to do it. The potential function is : V(x,y,z) = cos(10x) + cos(10y) + cos(10z) + 2*(x^2 + y^2 + z^2) I unsuccessfully attempted something like: import numpy import matplotlib.pyplot.contour def V(x,y,z): return numpy.cos(10*x) + numpy.cos(10*y) + numpy.cos(10*z) + 2*(x**2 + y**2 + z**2) X, Y, Z = numpy.mgrid[-1:1:100j, -1:1:100j, -1:1:100j] But then, I don't know how to do the next step to plot it? matplotlib.pyplot.contour(X,Y,Z,V)
An error will arise when you try to pass contour three-dimensional arrays, as it expects two-dimensional arrays. With this in mind, try: from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt from matplotlib import cm import numpy as np def V(x,y,z): return np.cos(10*x) + np.cos(10*y) + np.cos(10*z) + 2*(x**2 + y**2 + z**2) X,Y = np.mgrid[-1:1:100j, -1:1:100j] Z_vals = [ -0.5, 0, 0.9 ] num_subplots = len( Z_vals) fig = plt.figure(figsize=(10, 4)) for i,z in enumerate( Z_vals): ax = fig.add_subplot(1 , num_subplots , i+1, projection='3d') ax.contour(X, Y, V(X,Y,z), cmap=cm.gnuplot) ax.set_title('z = %.2f'%z, fontsize=30) fig.savefig('contours.png', facecolor='grey', edgecolor='none') Instead, use ax.contourf(...) to show the surfaces, which looks nicer in my opinion. There is no direct way to visualize a function of 3 variables, as it is an object (surface) which lives in 4 dimensions. One must play with slices of the function to see what's going on. By a slice, I mean a projection of the function onto a lower dimensional space. A slice is achieved by setting one or more of the function variables as a constant.
I'm not sure this is what the OP needed, but I think a possible solution might be this one: import numpy as np import matplotlib import matplotlib.pyplot as plt def compute_torus(precision, c, a): U = np.linspace(0, 2*np.pi, precision) V = np.linspace(0, 2*np.pi, precision) U, V = np.meshgrid(U, V) X = (c+a*np.cos(V))*np.cos(U) Y = (c+a*np.cos(V))*np.sin(U) Z = a*np.sin(V) return X, Y, Z x, y, z = compute_torus(100, 2, 1) fig = plt.figure() color_dimension = z # Here goes the potential minn, maxx = color_dimension.min(), color_dimension.max() norm = matplotlib.colors.Normalize(minn, maxx) m = plt.cm.ScalarMappable(norm=norm, cmap='jet') m.set_array([]) fcolors = m.to_rgba(color_dimension) # plot fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(x,y,z, rstride=1, cstride=1, facecolors=fcolors, vmin=minn, vmax=maxx, shade=False) Setting color_dimension to the values of the potential function, using this code can be plotted over a torus. In general, it can be plotted over any 3D shape of (x,y,z), but of course if the 3D space is fully filled with points everywhere, it's unlikely the image will be clear.
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()
Plotting function of 3 dimensions over given domain with matplotlib
I am trying to visualize a function of 3 parameters over a cube in R^3 to get an idea of the smoothness of the function. An example of this problem is shown in the sample code below %pylab from mpl_toolkits.mplot3d import Axes3D import itertools x = np.linspace(0,10,50) y = np.linspace(0,15,50) z = np.linspace(0,8,50) points = [] for element in itertools.product(x, y, z): points.append(element) def f(vals): return np.cos(vals[0]) + np.sin(vals[1]) + vals[2]**0.5 fxyz = map(f, points) xi, yi, zi = zip(*points) fig = plt.figure(figsize=(12, 8)) ax = fig.add_subplot(111, projection='3d') ax.scatter(xi, yi, zi, c=fxyz, alpha=0.5) plt.show() The problem with this approach is that the inside of the cube cannot be visualized. Is there a better way to graph a function over some dense subset of R^3?
As #HYRY and #nicoguaro suggested in the comments above, Mayavi is much better suited for this type of work. There is a good set of examples here that I used for reference. Here is what I came up with import numpy as np from mayavi import mlab x = np.linspace(0,10,50) y = np.linspace(0,15,50) z = np.linspace(0,8,50) X, Y, Z = np.meshgrid(x, y, z) s = np.cos(X) + np.sin(Y) + Z**0.5 b1 = np.percentile(s, 20) b2 = np.percentile(s, 80) mlab.pipeline.volume(mlab.pipeline.scalar_field(s), vmin=b1, vmax=b2) mlab.axes() mlab.show() After which I rotated the figure to desired angles with the GUI and saved desired views
Plotting a polynomial in Python
I am new to Python plotting apart from some basic knowledge of matplotlib.pyplot. My question is how to plot some higher degree polynomials? One method I saw was expressing y in terms of x and then plotting the values. But I have 2 difficulties: y and x cannot be separated. I am expecting a closed curve(actually a complicated curve) The polynomial I am trying to plot is: c0 + c1*x + c2*y +c3*x*x + c4*x*y + c5*y*y + c6*x**3 + c7*x**2*y + ..... c26*x*y**5 + c27*y**6 All coefficients c0 to c27 are known. How do I plot this curve? Also could you please suggest me resources from where I can learn plotting and visualization in Python? Clarification: Sorry everyone for not making it clear enough. It is not an equation of a surface (which involves 3 variables: x, y and z). I should have put a zero at the end: c0 + c1*x + c2*y +c3*x*x + c4*x*y + c5*y*y + c6*x**3 + c7*x**2*y + ..... c26*x*y**5 + c27*y**6 =0
I'm not sure I fully understood your question, but I think you want a surface plot import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D x = np.arange(-5, 5, 0.25) y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(x, y) F = 3 + 2*X + 4*X*Y + 5*X*X fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.plot_surface(X, Y, F) plt.show() And for the resources: official documentation and pyvideos
Your equation represents a 3D surface, which you can plot creating first a mesh grid of x and y values, easily achieved using numpy: X,Y = np.meshgrid( np.linspace( xmin, xmax, 100), np.linspace( ymin, ymax, 200) ) X and Y are both 2D arrays containing the X and Y coordinates, respectively. Then you can calculate z values for each point in this mesh, using the known coefficients: Z = c0 + c1*X + c2*Y +c3*X*X + c4*X*Y + c5*Y*Y + c6*X**3 + c7*X**2*Y + ..... c26*X*Y**5 + c27*Y**6 After that you can plot it using matplotlib: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt ax = plt.subplot(111, projection='3d') ax.plot_surface( X, Y, Z ) plt.show()