Plotting A Hyperboloid - python

Teacher in class gave this formula
w = x**2 + y**2 - z**2
and showed its 3d graphic in class seen below. How do I plot this using Matplotlib (minus the intersecting plane)? I guess first a specific value for w needs to be selected, for example 10, otherwise 3d plotting would not be possible. Then should I convert to polar coordinates because of the z**2 in the formula? I tried this and failed. Any help would be appreciated. Also, does this shape have a name?

Got it. Found some good stuff here, and following the formulas presented, I have the Python code below.
http://msenux.redwoods.edu/Math4Textbook/Plotting/ParametricSurfaces.pdf
from __future__ import division
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=plt.figaspect(1)) # Square figure
ax = fig.add_subplot(111, projection='3d')
r=1;
u=np.linspace(-2,2,200);
v=np.linspace(0,2*np.pi,60);
[u,v]=np.meshgrid(u,v);
a = 1
b = 1
c = 1
x = a*np.cosh(u)*np.cos(v)
y = b*np.cosh(u)*np.sin(v)
z = c*np.sinh(u)
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b')
plt.show()

Related

How do I remove overflow along the z-axis for a 3D matplotlib surface?

I'm trying to graph a 3d mesh surface with matplotlib and constrain the limits of the graph. The X and Y axes are correctly constrained, but there is overflow in the Z-Axis.
What am I missing? Here's my code:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(10,10))
x = np.linspace(-6,6,100)
y = np.linspace(-6,6,100)
X,Y = np.meshgrid(x,y)
def f(x,y):
return x**2 + 3*y
Z = f(X,Y)
ax = plt.axes(projection = '3d')
ax.plot_surface(X,Y,Z,cmap='viridis')
ax.title.set_text("z=x**2+3y")
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_zlim3d(zmin=-3,zmax=5)
ax.set_xlim3d(xmin=-6,xmax=6)
ax.set_ylim3d(ymin=-6,ymax=6)
plt.show()
The graph:
Edit:
When I add clipping/min/max to the Z values, the graph is a little better, but it sets z values outside the bounds to the bounds themselves. Both of the following suggestions do this. Perhaps it's because I'm on a mac?
z_tmp = np.maximum(np.minimum(5,Z),-3)
z_temp = np.clip(Z, -3, 5, None)
Your data is outside the axis boundaries. Try rotate the view and you will notice.
z = x**2 + 3*y
If you want to only show a defined area of the data you could add a max() min() limitation on the Z data to exclude the data outside your wanted limitations.
Z = f(X,Y)
z_tmp = np.maximum(np.minimum(5,Z),-3)
ax = plt.axes(projection = '3d')
ax.plot_surface(X,Y,z_tmp,cmap='viridis')
I'm not sure the matplotlib behaves as it should in your default case.

strange plot surface of matplotlib

I'm trying to generate a 3D height figure, I have a regular grid, the height data collected by the sensor and data store in a file which name is "data.txt". data stored one data per line. the file link on github
import numpy as np
import matplotlib.pyplot as pit
from mpl_toolkits.mplot3d import Axes3D
from scipy.stats import multivariate_normal
from matplotlib import cm
x = np.linspace(0,350,18)
y = np.linspace(0,350,15)
z = np.loadtxt('data.txt')
xx,yy = np.meshgrid(x,y)
fig = pit.figure()
ax = fig.add_subplot(111,projection='3d')
ax.scatter(xx,yy,z)
use the code above, I got a scatter. It looks good! I found this , I want convert the figure to surface, than I add the code below, but it looks very strange
xa = np.reshape(xx, (18,15))
ya = np.reshape(yy, (18,15))
za = np.reshape(z, (18,15))
surf=ax.plot_surface(xa,ya,za,cmap="summer",linewidth=0,antialiased=False, alpha=0.5)
fig.colorbar(surf)
pit.show()
the image
i don't know what happened, it look too strange! Should i smooth it?
You need to use xx and yy defined earlier and reshape z to the same shape as xx:
za = z.reshape(xx.shape)
fig = pit.figure()
ax = fig.add_subplot(111,projection='3d')
surf=ax.plot_surface(xx,yy,za,cmap="summer",linewidth=0,antialiased=False, alpha=0.5)
fig.colorbar(surf)
pit.show()
Note that I have rotate the chart for better clarity.
I think you need scipy.griddata. Try this code:
from scipy.interpolate import griddata
za = griddata(x, y, z, (xx, yy), method='linear')
surf=ax.plot_surface(xx,yy,za,cmap="summer",linewidth=0,antialiased=False, alpha=0.5)
fig.colorbar(surf)
plt.show()

Plotly plot_trisurf isn't working with arange arrays

I've basically just copied the example code found on the Matplotlib website, but I replaced their radii and angles with simple arange arrays.
I've tried different array functions and I can't seem to figure out anything.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from Equation import Expression
x = np.arange(0,100,0.01)
y = np.arange(0,100,0.01)
x2 = np.append(0,x.flatten())
y2 = np.append(0,y.flatten())
z = x2 + y2
print(z)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)
plt.show()
I'm just trying to make a graph of z = x + y but I'm getting a confusing error.
"RuntimeError: Error in qhull Delaunay triangulation calculation: singular input data (exitcode=2); use python verbose option (-v) to see original qhull error."
Edit: I've also tried it without calling flatten() but I get the same result though.
The error you are getting is because your z is not a surface but a line. You need to use at least 3 points that would define a plane. One option could be to use np.meshgrid to create your surface for plotting and then flatten everything to insert into the function. Try going back to some example code here. Note you may also want to change your resolution depending on the detail of your surface.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0,100,1)
y = np.arange(0,100,1)
x2 = np.append(0,x.flatten())
y2 = np.append(0,y.flatten())
x2,y2 = np.meshgrid(x2,y2) #This is what you were missing
z = x2 + y2
fig = plt.figure(figsize=(12,12))
ax = fig.gca(projection='3d')
ax.plot_trisurf(x2.flatten(), y2.flatten(), z.flatten(), linewidth=0.2, antialiased=True) #flatten all the arrays here
plt.show()

axes3d.plot_wireframe(X,Y,Z) Error

I'm trying to learn Python through a tutorial on youtube and I'm having some difficulies working with 3D graphs. Long stories short, I continuously get (if
Z.ndim != 2:
AttributeError: 'list' object has no attribute 'ndim')
error while trying to launch this simple program:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
chart = fig.add_subplot(1,1,1,projection = '3d')
X,Y,Z = [1,2,3,4,5,6,7,8],[2,5,3,8,9,5,6,1],[3,6,2,7,5,4,5,6]
chart.plot_wireframe(X,Y,Z)
plt.show()
I know that it is related to the Axes3.plot_wireframe() method but Could anyone explain to me what's happening.
I walked around this problem by doing two things.
import numpy as np
making the z-axis a multidimensional array
#My 3d graph
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import numpy as np
figure = plt.figure()
axis = figure.add_subplot(111, projection = '3d')
x = [1,2,3,4,5,6,7,8,9,10]
y = [5,6,7,8,2,5,6,3,7,2]
z = np.array([[1,2,6,3,2,7,3,3,7,2],[1,2,6,3,2,7,3,3,7,2]])
axis.plot_wireframe(x, y, z)
axis.set_xlabel('x-axis')
axis.set_ylabel('y-axis')
axis.set_zlabel('z-axis')
plt.show()
Take special note of the z variable. If z is not multidimensional, it will throw an error.
Hope it solves your problem
Running your code with either Python 2.7.10 or Python 3.6.0, with matplotlib version 2.0.2, yields the same image with no error:
This is not a wireframe though, and a simple ax.plot(X, Y, Z) would have generated it. As DavidG and ImportanceOfBeingErnest cleverly mentioned, it makes no sense to pass 1D lists to the wireframe function, as X, Y and Z should be two-dimensional.
The following code (an example taken from the matplotlib official documentation) shows exactly how the parameters of the plot_wireframe function should be (using numpy arrays):
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
'''
def get_test_data(delta=0.05):
from matplotlib.mlab import bivariate_normal
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1
X = X * 10
Y = Y * 10
Z = Z * 500
return X, Y, Z
'''
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y, z = axes3d.get_test_data(0.05)
ax.plot_wireframe(x,y,z, rstride=2, cstride=2)
plt.show()
The output image is a true wireframe:
Printing x.shape, for instance, yields you (120, 120), showing that the array is two-dimensional and have 120 positions in the first dimension and 120 positions in the second one.
I had the exact problem (example from video not working though exactly copied). Without looking into the source code I'm assuming a reality check was added to matplotlib 2.1.0 that NOW stops 1D arrays from being used in plot_wireframe. Changing that method call to simply "plot" did indeed fix the problem.
The command
ax.plot_wireframe(x,y,z, rstride=2, cstride=2)
is creating the problems with the latest versions.
Try using:
ax.plot(x,y,z)
This will definitely solve your issues.
Python has been known for being inconsistent with the older libraries.
I am getting this image as the output:
This is the 3d Image I am getting

Plotting surface of implicitly defined volume

Having a volume implicitly defined by
x*y*z <= 1
for
-5 <= x <= 5
-5 <= y <= 5
-5 <= z <= 5
how would I go about plotting its outer surface using available Python modules, preferably mayavi?
I am aware of the function mlab.mesh, but I don't understand its input. It requires three 2D arrays, that I don't understand how to create having the above information.
EDIT:
Maybe my problem lies with an unsufficient understanding of the meshgrid()-function or the mgrid-class of numpy. I see that I have to use them in some way, but I do not completely grasp their purpose or what such a grid represents.
EDIT:
I arrived at this:
import numpy as np
from mayavi import mlab
x, y, z = np.ogrid[-5:5:200j, -5:5:200j, -5:5:200j]
s = x*y*z
src = mlab.pipeline.scalar_field(s)
mlab.pipeline.iso_surface(src, contours=[1., ],)
mlab.show()
This results in an isosurface (for x*y*z=1) of a volume though, which is not quite what I was looking for. What I am looking for is basically a method to draw an arbitrary surface, like a "polygon in 3d" if there is such a thing.
I created the following code, which plots a surface (works with mayavi, too). I would need to modify this code to my particular problem, but to do that I need to understand why and how a 3d surface is defined by three 2d-arrays? What do these arrays (x, y and z) represent?
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
phi, theta = np.mgrid[0:np.pi:11j, 0:2*np.pi:11j]
x = np.sin(phi) * np.cos(theta)
y = np.sin(phi) * np.sin(theta)
z = np.cos(phi)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(x,y,z)
fig.show()
The outer surface, implicitly defined by
x*y*z = 1,
cannot be defined explicitly globally. To see this, consider x and y given, then:
z = 1/(x*y),
which is not defined for x = 0 or y = 0. Therefore, you can only define your surface locally for domains that do not include the singularity, e.g. for the domain
0 < x <= 5
0 < y <= 5
z is indeed defined (a hyperbolic surface). Similarly, you need to plot the surfaces for the other domains, until you have patched together
-5 <= x <= 5
-5 <= y <= 5
Note that your surface is not defined for x = 0 and y = 0, i.e. the axis of your coordinate system, so you cannot patch your surfaces together to get a globally defined surface.
Using numpy and matplotlib, you can plot one of these surfaces as follows (adopted from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#surface-plots):
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(0.25, 5, 0.25)
Y = np.arange(0.25, 5, 0.25)
X, Y = np.meshgrid(X, Y)
Z = 1/(X*Y)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(0, 10)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
I'm not familiar with mayavi, but I would assume that creating the meshes with numpy would work the same.
The test case in the Mayavi docs where the function test_mesh() is defined is capable of producing a sphere. This is done by replacing
r = sin(m0*phi)**m1 + cos(m2*phi)**m3 + sin(m4*theta)**m5 + cos(m6*theta)**m7
with r = 1.0 say.
However, your problem is you need to understand that the equations you are writing define a volume when you want to draw a sphere. You need to reformulate them to give a parametric equation of a sphere. This is essentially what is done in the above example, but it may be worth your while to try it yourself. As a hint consider the equation of a circle and extend it.

Categories