draw a 3d plot in matlab with constant z
Matplotlib was initially designed with merely two-dimensional plotting in mind. Around the fourth dimension of the 1.0 release, some three-dimensional plotting utilities were congenital on pinnacle of Matplotlib'south 2-dimensional display, and the outcome is a convenient (if somewhat limited) set of tools for 3-dimensional data visualization. three-dimensional plots are enabled by importing the mplot3d toolkit, included with the principal Matplotlib installation:
In [1]:
from mpl_toolkits import mplot3d
Once this submodule is imported, a three-dimensional axes tin can be created past passing the keyword projection='3d' to whatsoever of the normal axes cosmos routines:
In [ii]:
% matplotlib inline import numpy as np import matplotlib.pyplot as plt
In [three]:
fig = plt . figure () ax = plt . axes ( projection = '3d' )
With this three-dimensional axes enabled, we tin can now plot a variety of three-dimensional plot types. Three-dimensional plotting is 1 of the functionalities that benefits immensely from viewing figures interactively rather than statically in the notebook; call back that to use interactive figures, you can use %matplotlib notebook rather than %matplotlib inline when running this code.
Three-dimensional Points and Lines¶
The virtually basic three-dimensional plot is a line or collection of scatter plot created from sets of (x, y, z) triples. In analogy with the more than common ii-dimensional plots discussed earlier, these can exist created using the ax.plot3D and ax.scatter3D functions. The call signature for these is well-nigh identical to that of their two-dimensional counterparts, so you can refer to Simple Line Plots and Uncomplicated Besprinkle Plots for more than information on decision-making the output. Here nosotros'll plot a trigonometric spiral, forth with some points fatigued randomly about the line:
In [4]:
ax = plt . axes ( project = '3d' ) # Information for a three-dimensional line zline = np . linspace ( 0 , fifteen , 1000 ) xline = np . sin ( zline ) yline = np . cos ( zline ) ax . plot3D ( xline , yline , zline , 'grey' ) # Information for three-dimensional scattered points zdata = 15 * np . random . random ( 100 ) xdata = np . sin ( zdata ) + 0.1 * np . random . randn ( 100 ) ydata = np . cos ( zdata ) + 0.1 * np . random . randn ( 100 ) ax . scatter3D ( xdata , ydata , zdata , c = zdata , cmap = 'Greens' );
Notice that past default, the scatter points take their transparency adjusted to requite a sense of depth on the page. While the three-dimensional upshot is sometimes hard to meet within a static prototype, an interactive view can lead to some nice intuition about the layout of the points.
Iii-dimensional Contour Plots¶
Analogous to the contour plots nosotros explored in Density and Contour Plots, mplot3d contains tools to create 3-dimensional relief plots using the same inputs. Similar two-dimensional ax.profile plots, ax.contour3D requires all the input data to be in the course of 2-dimensional regular grids, with the Z information evaluated at each bespeak. Here we'll show a three-dimensional contour diagram of a 3-dimensional sinusoidal function:
In [5]:
def f ( 10 , y ): return np . sin ( np . sqrt ( ten ** 2 + y ** 2 )) x = np . linspace ( - 6 , half dozen , 30 ) y = np . linspace ( - 6 , 6 , 30 ) X , Y = np . meshgrid ( x , y ) Z = f ( X , Y )
In [6]:
fig = plt . figure () ax = plt . axes ( projection = '3d' ) ax . contour3D ( X , Y , Z , 50 , cmap = 'binary' ) ax . set_xlabel ( 'x' ) ax . set_ylabel ( 'y' ) ax . set_zlabel ( 'z' );
Sometimes the default viewing angle is not optimal, in which example we can use the view_init method to prepare the elevation and azimuthal angles. In the following example, we'll utilise an tiptop of 60 degrees (that is, 60 degrees higher up the x-y aeroplane) and an azimuth of 35 degrees (that is, rotated 35 degrees counter-clockwise about the z-axis):
Out[7]:
Again, note that this type of rotation tin can be accomplished interactively by clicking and dragging when using 1 of Matplotlib's interactive backends.
Wireframes and Surface Plots¶
2 other types of iii-dimensional plots that work on gridded information are wireframes and surface plots. These take a filigree of values and projection it onto the specified 3-dimensional surface, and tin make the resulting three-dimensional forms quite like shooting fish in a barrel to visualize. Here'southward an example of using a wireframe:
In [eight]:
fig = plt . figure () ax = plt . axes ( projection = '3d' ) ax . plot_wireframe ( X , Y , Z , color = 'black' ) ax . set_title ( 'wireframe' );
A surface plot is like a wireframe plot, but each face up of the wireframe is a filled polygon. Adding a colormap to the filled polygons can aid perception of the topology of the surface being visualized:
In [9]:
ax = plt . axes ( project = '3d' ) ax . plot_surface ( X , Y , Z , rstride = 1 , cstride = i , cmap = 'viridis' , edgecolor = 'none' ) ax . set_title ( 'surface' );
Note that though the grid of values for a surface plot needs to exist two-dimensional, it need non exist rectilinear. Hither is an example of creating a partial polar filigree, which when used with the surface3D plot can give us a slice into the function nosotros're visualizing:
In [x]:
r = np . linspace ( 0 , 6 , 20 ) theta = np . linspace ( - 0.ix * np . pi , 0.eight * np . pi , 40 ) r , theta = np . meshgrid ( r , theta ) 10 = r * np . sin ( theta ) Y = r * np . cos ( theta ) Z = f ( 10 , Y ) ax = plt . axes ( projection = '3d' ) ax . plot_surface ( X , Y , Z , rstride = 1 , cstride = i , cmap = 'viridis' , edgecolor = 'none' );
Surface Triangulations¶
For some applications, the evenly sampled grids required by the higher up routines is overly restrictive and inconvenient. In these situations, the triangulation-based plots tin can be very useful. What if rather than an fifty-fifty draw from a Cartesian or a polar grid, nosotros instead take a ready of random draws?
In [11]:
theta = 2 * np . pi * np . random . random ( 1000 ) r = six * np . random . random ( chiliad ) x = np . ravel ( r * np . sin ( theta )) y = np . ravel ( r * np . cos ( theta )) z = f ( ten , y )
We could create a scatter plot of the points to get an idea of the surface we're sampling from:
In [12]:
ax = plt . axes ( projection = '3d' ) ax . scatter ( x , y , z , c = z , cmap = 'viridis' , linewidth = 0.v );
This leaves a lot to be desired. The function that will help u.s.a. in this example is ax.plot_trisurf, which creates a surface by offset finding a set of triangles formed betwixt next points (call back that x, y, and z here are 1-dimensional arrays):
In [13]:
ax = plt . axes ( projection = '3d' ) ax . plot_trisurf ( x , y , z , cmap = 'viridis' , edgecolor = 'none' );
The upshot is certainly not as clean as when information technology is plotted with a grid, but the flexibility of such a triangulation allows for some really interesting iii-dimensional plots. For example, information technology is actually possible to plot a three-dimensional Möbius strip using this, as we'll see next.
Example: Visualizing a Möbius strip¶
A Möbius strip is similar to a strip of newspaper glued into a loop with a half-twist. Topologically, it'due south quite interesting considering despite appearances information technology has only a single side! Here we will visualize such an object using Matplotlib'due south iii-dimensional tools. The key to creating the Möbius strip is to think about information technology'southward parametrization: it'southward a 2-dimensional strip, and so nosotros need 2 intrinsic dimensions. Let's call them $\theta$, which ranges from $0$ to $two\pi$ around the loop, and $w$ which ranges from -one to 1 across the width of the strip:
In [xiv]:
theta = np . linspace ( 0 , 2 * np . pi , 30 ) w = np . linspace ( - 0.25 , 0.25 , 8 ) due west , theta = np . meshgrid ( w , theta )
At present from this parametrization, we must determine the (x, y, z) positions of the embedded strip.
Thinking about it, we might realize that there are two rotations happening: one is the position of the loop about its middle (what we've chosen $\theta$), while the other is the twisting of the strip most its centrality (nosotros'll call this $\phi$). For a Möbius strip, we must have the strip makes half a twist during a full loop, or $\Delta\phi = \Delta\theta/2$.
At present nosotros use our recollection of trigonometry to derive the three-dimensional embedding. We'll define $r$, the distance of each point from the center, and use this to notice the embedded $(x, y, z)$ coordinates:
In [sixteen]:
# radius in ten-y aeroplane r = one + w * np . cos ( phi ) x = np . ravel ( r * np . cos ( theta )) y = np . ravel ( r * np . sin ( theta )) z = np . ravel ( w * np . sin ( phi ))
Finally, to plot the object, we must make sure the triangulation is correct. The all-time fashion to do this is to define the triangulation inside the underlying parametrization, then allow Matplotlib projection this triangulation into the three-dimensional space of the Möbius strip. This can be accomplished as follows:
In [17]:
# triangulate in the underlying parametrization from matplotlib.tri import Triangulation tri = Triangulation ( np . ravel ( w ), np . ravel ( theta )) ax = plt . axes ( projection = '3d' ) ax . plot_trisurf ( ten , y , z , triangles = tri . triangles , cmap = 'viridis' , linewidths = 0.2 ); ax . set_xlim ( - i , ane ); ax . set_ylim ( - 1 , 1 ); ax . set_zlim ( - 1 , 1 );
Combining all of these techniques, it is possible to create and brandish a wide variety of three-dimensional objects and patterns in Matplotlib.
Source: https://jakevdp.github.io/PythonDataScienceHandbook/04.12-three-dimensional-plotting.html
0 Response to "draw a 3d plot in matlab with constant z"
Post a Comment