How to Draw Plane in 3d Plot Python
Matplotlib was initially designed with only two-dimensional plotting in mind. Around the time of the i.0 release, some iii-dimensional plotting utilities were congenital on top of Matplotlib's two-dimensional display, and the issue is a convenient (if somewhat limited) set of tools for three-dimensional data visualization. three-dimensional plots are enabled past importing the mplot3d
toolkit, included with the master Matplotlib installation:
In [1]:
from mpl_toolkits import mplot3d
Once this submodule is imported, a 3-dimensional axes can exist created by passing the keyword project='3d'
to whatever of the normal axes creation routines:
In [two]:
% matplotlib inline import numpy as np import matplotlib.pyplot as plt
In [3]:
fig = plt . figure () ax = plt . axes ( projection = '3d' )
With this three-dimensional axes enabled, nosotros can now plot a variety of 3-dimensional plot types. Three-dimensional plotting is one of the functionalities that benefits immensely from viewing figures interactively rather than statically in the notebook; call up that to use interactive figures, you can use %matplotlib notebook
rather than %matplotlib inline
when running this code.
Three-dimensional Points and Lines¶
The most bones three-dimensional plot is a line or drove of scatter plot created from sets of (x, y, z) triples. In analogy with the more common ii-dimensional plots discussed earlier, these can be created using the ax.plot3D
and ax.scatter3D
functions. The call signature for these is nearly identical to that of their 2-dimensional counterparts, then you lot can refer to Simple Line Plots and Elementary Scatter Plots for more data on decision-making the output. Here we'll plot a trigonometric screw, forth with some points drawn randomly nearly the line:
In [4]:
ax = plt . axes ( projection = '3d' ) # Data for a three-dimensional line zline = np . linspace ( 0 , 15 , 1000 ) xline = np . sin ( zline ) yline = np . cos ( zline ) ax . plot3D ( xline , yline , zline , 'greyness' ) # 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.one * np . random . randn ( 100 ) ax . scatter3D ( xdata , ydata , zdata , c = zdata , cmap = 'Greens' );
Find that by default, the scatter points have their transparency adjusted to requite a sense of depth on the page. While the three-dimensional effect is sometimes difficult to see within a static paradigm, an interactive view can lead to some dainty intuition about the layout of the points.
Iii-dimensional Profile Plots¶
Analogous to the profile plots nosotros explored in Density and Profile Plots, mplot3d
contains tools to create 3-dimensional relief plots using the same inputs. Like 2-dimensional ax.contour
plots, ax.contour3D
requires all the input data to exist in the form of two-dimensional regular grids, with the Z information evaluated at each point. Here we'll show a three-dimensional contour diagram of a three-dimensional sinusoidal function:
In [5]:
def f ( x , y ): return np . sin ( np . sqrt ( ten ** 2 + y ** 2 )) x = np . linspace ( - 6 , half dozen , 30 ) y = np . linspace ( - 6 , 6 , xxx ) Ten , Y = np . meshgrid ( x , y ) Z = f ( X , Y )
In [6]:
fig = plt . effigy () ax = plt . axes ( project = '3d' ) ax . contour3D ( 10 , Y , Z , 50 , cmap = 'binary' ) ax . set_xlabel ( 'x' ) ax . set_ylabel ( 'y' ) ax . set_zlabel ( 'z' );
Sometimes the default viewing angle is non optimal, in which case we can use the view_init
method to ready the superlative and azimuthal angles. In the following example, we'll utilize an elevation of 60 degrees (that is, 60 degrees to a higher place the x-y aeroplane) and an azimuth of 35 degrees (that is, rotated 35 degrees counter-clockwise about the z-axis):
Out[7]:
Again, annotation that this blazon of rotation can exist accomplished interactively by clicking and dragging when using i of Matplotlib'southward interactive backends.
Wireframes and Surface Plots¶
Two other types of 3-dimensional plots that piece of work on gridded data are wireframes and surface plots. These accept a grid of values and project it onto the specified iii-dimensional surface, and tin brand the resulting three-dimensional forms quite piece of cake to visualize. Here'south an example of using a wireframe:
In [viii]:
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 of the wireframe is a filled polygon. Adding a colormap to the filled polygons tin can aid perception of the topology of the surface existence visualized:
In [9]:
ax = plt . axes ( projection = '3d' ) ax . plot_surface ( 10 , Y , Z , rstride = 1 , cstride = 1 , cmap = 'viridis' , edgecolor = 'none' ) ax . set_title ( 'surface' );
Note that though the grid of values for a surface plot needs to exist 2-dimensional, information technology need not be rectilinear. Here is an case of creating a partial polar grid, which when used with the surface3D
plot tin can requite u.s.a. a piece into the function we're visualizing:
In [10]:
r = np . linspace ( 0 , half-dozen , twenty ) theta = np . linspace ( - 0.9 * np . pi , 0.viii * np . pi , xl ) r , theta = np . meshgrid ( r , theta ) 10 = r * np . sin ( theta ) Y = r * np . cos ( theta ) Z = f ( X , Y ) ax = plt . axes ( projection = '3d' ) ax . plot_surface ( 10 , Y , Z , rstride = 1 , cstride = one , cmap = 'viridis' , edgecolor = 'none' );
Surface Triangulations¶
For some applications, the evenly sampled grids required past the above routines is overly restrictive and inconvenient. In these situations, the triangulation-based plots can exist very useful. What if rather than an even depict from a Cartesian or a polar grid, we instead have a gear up of random draws?
In [11]:
theta = ii * np . pi * np . random . random ( thousand ) r = 6 * np . random . random ( 1000 ) ten = np . ravel ( r * np . sin ( theta )) y = np . ravel ( r * np . cos ( theta )) z = f ( x , y )
We could create a besprinkle 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.5 );
This leaves a lot to be desired. The function that will assistance usa in this case is ax.plot_trisurf
, which creates a surface past first finding a fix of triangles formed between adjacent points (remember that x, y, and z here are i-dimensional arrays):
In [13]:
ax = plt . axes ( projection = '3d' ) ax . plot_trisurf ( x , y , z , cmap = 'viridis' , edgecolor = 'none' );
The result is certainly non as clean every bit when it is plotted with a filigree, only the flexibility of such a triangulation allows for some actually interesting 3-dimensional plots. For example, it is really possible to plot a iii-dimensional Möbius strip using this, equally we'll see next.
Case: Visualizing a Möbius strip¶
A Möbius strip is similar to a strip of paper glued into a loop with a one-half-twist. Topologically, it'southward quite interesting considering despite appearances it has only a single side! Here we volition visualize such an object using Matplotlib's three-dimensional tools. The key to creating the Möbius strip is to think near it's parametrization: it'due south a two-dimensional strip, so we demand 2 intrinsic dimensions. Allow'south call them $\theta$, which ranges from $0$ to $ii\pi$ around the loop, and $w$ which ranges from -ane to ane across the width of the strip:
In [fourteen]:
theta = np . linspace ( 0 , 2 * np . pi , 30 ) w = np . linspace ( - 0.25 , 0.25 , eight ) w , theta = np . meshgrid ( w , theta )
Now from this parametrization, we must determine the (x, y, z) positions of the embedded strip.
Thinking most information technology, nosotros might realize that there are ii rotations happening: one is the position of the loop near its center (what we've called $\theta$), while the other is the twisting of the strip about its axis (we'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$.
Now we use our recollection of trigonometry to derive the three-dimensional embedding. We'll define $r$, the altitude of each bespeak from the center, and employ this to observe the embedded $(x, y, z)$ coordinates:
In [16]:
# radius in 10-y plane r = ane + w * np . cos ( phi ) x = np . ravel ( r * np . cos ( theta )) y = np . ravel ( r * np . sin ( theta )) z = np . ravel ( due west * np . sin ( phi ))
Finally, to plot the object, we must make sure the triangulation is correct. The best way to practice this is to ascertain the triangulation inside the underlying parametrization, and so permit Matplotlib project 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 ( project = '3d' ) ax . plot_trisurf ( 10 , y , z , triangles = tri . triangles , cmap = 'viridis' , linewidths = 0.ii ); ax . set_xlim ( - 1 , i ); ax . set_ylim ( - 1 , 1 ); ax . set_zlim ( - i , 1 );
Combining all of these techniques, information technology is possible to create and brandish a wide diverseness of 3-dimensional objects and patterns in Matplotlib.
Source: https://jakevdp.github.io/PythonDataScienceHandbook/04.12-three-dimensional-plotting.html
Postar um comentário for "How to Draw Plane in 3d Plot Python"