draw 3d points from console
Matplotlib was initially designed with only 2-dimensional plotting in mind. Around the time of the one.0 release, some iii-dimensional plotting utilities were built on top of Matplotlib's two-dimensional brandish, and the result is a convenient (if somewhat express) prepare of tools for three-dimensional data visualization. three-dimensional plots are enabled past importing the mplot3d
toolkit, included with the main Matplotlib installation:
In [1]:
from mpl_toolkits import mplot3d
Once this submodule is imported, a three-dimensional axes can exist created by passing the keyword projection='3d'
to any of the normal axes creation routines:
In [ii]:
% matplotlib inline import numpy equally np import matplotlib.pyplot as plt
In [iii]:
fig = plt . figure () ax = plt . axes ( project = '3d' )
With this three-dimensional axes enabled, nosotros tin now plot a variety of three-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 employ interactive figures, y'all tin can use %matplotlib notebook
rather than %matplotlib inline
when running this code.
Three-dimensional Points and Lines¶
The most 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 common two-dimensional plots discussed earlier, these can be created using the ax.plot3D
and ax.scatter3D
functions. The call signature for these is almost identical to that of their two-dimensional counterparts, and so y'all can refer to Simple Line Plots and Simple Scatter Plots for more than data on controlling the output. Here we'll plot a trigonometric screw, along with some points drawn randomly almost the line:
In [iv]:
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 , 'grayness' ) # Data 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' );
Detect that by default, the besprinkle points have their transparency adjusted to give a sense of depth on the page. While the three-dimensional effect is sometimes difficult to come across within a static image, an interactive view can lead to some squeamish intuition about the layout of the points.
3-dimensional Contour Plots¶
Analogous to the profile plots we explored in Density and Contour Plots, mplot3d
contains tools to create iii-dimensional relief plots using the same inputs. Similar 2-dimensional ax.contour
plots, ax.contour3D
requires all the input data to be in the class of two-dimensional regular grids, with the Z data evaluated at each indicate. Here we'll show a three-dimensional contour diagram of a 3-dimensional sinusoidal role:
In [5]:
def f ( ten , y ): return np . sin ( np . sqrt ( x ** two + y ** 2 )) x = np . linspace ( - half-dozen , 6 , xxx ) y = np . linspace ( - 6 , 6 , 30 ) 10 , Y = np . meshgrid ( x , y ) Z = f ( X , Y )
In [6]:
fig = plt . figure () ax = plt . axes ( project = '3d' ) ax . contour3D ( 10 , Y , Z , 50 , cmap = 'binary' ) ax . set_xlabel ( '10' ) ax . set_ylabel ( 'y' ) ax . set_zlabel ( 'z' );
Sometimes the default viewing angle is not optimal, in which case we tin can use the view_init
method to set the height and azimuthal angles. In the following instance, we'll use an pinnacle of 60 degrees (that is, 60 degrees above the x-y plane) and an azimuth of 35 degrees (that is, rotated 35 degrees counter-clockwise most the z-axis):
Out[7]:
Again, note that this type of rotation can exist accomplished interactively past clicking and dragging when using one of Matplotlib'due south interactive backends.
Wireframes and Surface Plots¶
Ii other types of iii-dimensional plots that piece of work on gridded data are wireframes and surface plots. These take a grid of values and project it onto the specified 3-dimensional surface, and can brand the resulting three-dimensional forms quite easy to visualize. Here's an instance 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, merely each face of the wireframe is a filled polygon. Adding a colormap to the filled polygons can assistance perception of the topology of the surface being visualized:
In [9]:
ax = plt . axes ( projection = '3d' ) ax . plot_surface ( X , Y , Z , rstride = one , cstride = 1 , cmap = 'viridis' , edgecolor = 'none' ) ax . set_title ( 'surface' );
Notation that though the grid of values for a surface plot needs to be two-dimensional, it demand non exist rectilinear. Hither is an case of creating a partial polar grid, which when used with the surface3D
plot can give us a slice into the office nosotros're visualizing:
In [10]:
r = np . linspace ( 0 , half-dozen , 20 ) theta = np . linspace ( - 0.ix * np . pi , 0.viii * np . pi , 40 ) r , theta = np . meshgrid ( r , theta ) X = r * np . sin ( theta ) Y = r * np . cos ( theta ) Z = f ( X , Y ) ax = plt . axes ( projection = '3d' ) ax . plot_surface ( X , 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 be very useful. What if rather than an even draw from a Cartesian or a polar grid, we instead take a set of random draws?
In [11]:
theta = two * np . pi * np . random . random ( m ) r = half-dozen * np . random . random ( k ) x = np . ravel ( r * np . sin ( theta )) y = np . ravel ( r * np . cos ( theta )) z = f ( x , y )
We could create a scatter plot of the points to become an idea of the surface we're sampling from:
In [12]:
ax = plt . axes ( projection = '3d' ) ax . scatter ( ten , y , z , c = z , cmap = 'viridis' , linewidth = 0.five );
This leaves a lot to exist desired. The office that will help us in this example is ax.plot_trisurf
, which creates a surface past first finding a set of triangles formed between next points (remember that 10, y, and z here are one-dimensional arrays):
In [13]:
ax = plt . axes ( projection = '3d' ) ax . plot_trisurf ( ten , y , z , cmap = 'viridis' , edgecolor = 'none' );
The result is certainly not as make clean equally when it is plotted with a filigree, but the flexibility of such a triangulation allows for some really interesting three-dimensional plots. For case, it is actually possible to plot a iii-dimensional Möbius strip using this, as we'll run across next.
Example: Visualizing a Möbius strip¶
A Möbius strip is similar to a strip of paper glued into a loop with a half-twist. Topologically, it'southward quite interesting because despite appearances it has only a unmarried side! Here we will visualize such an object using Matplotlib's 3-dimensional tools. The key to creating the Möbius strip is to think about it'due south parametrization: it'southward a 2-dimensional strip, so we need ii intrinsic dimensions. Allow'southward call them $\theta$, which ranges from $0$ to $2\pi$ around the loop, and $w$ which ranges from -1 to i beyond the width of the strip:
In [14]:
theta = np . linspace ( 0 , two * np . pi , 30 ) due west = np . linspace ( - 0.25 , 0.25 , viii ) 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 at that place are ii rotations happening: 1 is the position of the loop most its eye (what we've chosen $\theta$), while the other is the twisting of the strip nigh its axis (we'll telephone call this $\phi$). For a Möbius strip, nosotros must have the strip makes half a twist during a full loop, or $\Delta\phi = \Delta\theta/two$.
At present nosotros use our recollection of trigonometry to derive the three-dimensional embedding. We'll define $r$, the distance of each bespeak from the center, and use this to find the embedded $(ten, y, z)$ coordinates:
In [16]:
# radius in x-y plane r = 1 + 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, nosotros must make sure the triangulation is right. The all-time mode to practise this is to ascertain the triangulation inside the underlying parametrization, and then let Matplotlib project this triangulation into the three-dimensional space of the Möbius strip. This tin exist accomplished as follows:
In [17]:
# triangulate in the underlying parametrization from matplotlib.tri import Triangulation tri = Triangulation ( np . ravel ( westward ), np . ravel ( theta )) ax = plt . axes ( projection = '3d' ) ax . plot_trisurf ( x , y , z , triangles = tri . triangles , cmap = 'viridis' , linewidths = 0.2 ); ax . set_xlim ( - ane , 1 ); ax . set_ylim ( - 1 , 1 ); ax . set_zlim ( - 1 , ane );
Combining all of these techniques, it is possible to create and display 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 3d points from console"
Post a Comment