Python Drawing 3d Graph Plane and Dot

Matplotlib was initially designed with only two-dimensional plotting in mind. Around the time of the 1.0 release, some iii-dimensional plotting utilities were built on height of Matplotlib's two-dimensional display, and the result is a convenient (if somewhat limited) gear up of tools for three-dimensional data visualization. three-dimensional plots are enabled by importing the mplot3d toolkit, included with the chief Matplotlib installation:

In [1]:

                            from              mpl_toolkits              import              mplot3d            

One time this submodule is imported, a three-dimensional axes can be created by passing the keyword projection='3d' to whatsoever of the normal axes cosmos routines:

In [2]:

                            %              matplotlib              inline              import              numpy              equally              np              import              matplotlib.pyplot              as              plt            

In [3]:

                                fig                =                plt                .                figure                ()                ax                =                plt                .                axes                (                projection                =                '3d'                )              

With this three-dimensional axes enabled, nosotros tin can now plot a diverseness 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; remember that to use interactive figures, y'all can employ %matplotlib notebook rather than %matplotlib inline when running this code.

Iii-dimensional Points and Lines¶

The nigh bones 3-dimensional plot is a line or collection of besprinkle plot created from sets of (x, y, z) triples. In analogy with the more common two-dimensional plots discussed earlier, these can exist created using the ax.plot3D and ax.scatter3D functions. The telephone call signature for these is well-nigh identical to that of their two-dimensional counterparts, so you can refer to Simple Line Plots and Simple Scatter Plots for more information on controlling the output. Here we'll plot a trigonometric screw, along with some points drawn randomly near the line:

In [iv]:

                                ax                =                plt                .                axes                (                projection                =                '3d'                )                # Data for a three-dimensional line                zline                =                np                .                linspace                (                0                ,                fifteen                ,                1000                )                xline                =                np                .                sin                (                zline                )                yline                =                np                .                cos                (                zline                )                ax                .                plot3D                (                xline                ,                yline                ,                zline                ,                'grayness'                )                # Data for 3-dimensional scattered points                zdata                =                15                *                np                .                random                .                random                (                100                )                xdata                =                np                .                sin                (                zdata                )                +                0.one                *                np                .                random                .                randn                (                100                )                ydata                =                np                .                cos                (                zdata                )                +                0.1                *                np                .                random                .                randn                (                100                )                ax                .                scatter3D                (                xdata                ,                ydata                ,                zdata                ,                c                =                zdata                ,                cmap                =                'Greens'                );              

Find that by default, the scatter points take their transparency adjusted to give a sense of depth on the page. While the 3-dimensional issue is sometimes difficult to run across within a static image, an interactive view can pb to some overnice intuition about the layout of the points.

Iii-dimensional Contour Plots¶

Coordinating to the contour plots we explored in Density and Contour Plots, mplot3d contains tools to create iii-dimensional relief plots using the same inputs. Like two-dimensional ax.contour plots, ax.contour3D requires all the input data to be in the class of ii-dimensional regular grids, with the Z data evaluated at each betoken. Here we'll show a three-dimensional contour diagram of a three-dimensional sinusoidal role:

In [5]:

                            def              f              (              x              ,              y              ):              render              np              .              sin              (              np              .              sqrt              (              x              **              ii              +              y              **              2              ))              x              =              np              .              linspace              (              -              6              ,              vi              ,              30              )              y              =              np              .              linspace              (              -              6              ,              6              ,              30              )              Ten              ,              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 non optimal, in which case we can use the view_init method to set the elevation and azimuthal angles. In the post-obit example, we'll use an elevation of 60 degrees (that is, 60 degrees above the x-y aeroplane) and an azimuth of 35 degrees (that is, rotated 35 degrees counter-clockwise about the z-axis):

Out[seven]:

Again, note that this type of rotation can be achieved interactively by clicking and dragging when using 1 of Matplotlib'due south interactive backends.

Wireframes and Surface Plots¶

Two other types of iii-dimensional plots that work on gridded data are wireframes and surface plots. These take a grid of values and projection it onto the specified three-dimensional surface, and can make the resulting three-dimensional forms quite easy to visualize. Here'due south an example of using a wireframe:

In [8]:

                                fig                =                plt                .                figure                ()                ax                =                plt                .                axes                (                projection                =                '3d'                )                ax                .                plot_wireframe                (                X                ,                Y                ,                Z                ,                color                =                'black'                )                ax                .                set_title                (                'wireframe'                );              

A surface plot is similar 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                (                projection                =                '3d'                )                ax                .                plot_surface                (                X                ,                Y                ,                Z                ,                rstride                =                1                ,                cstride                =                1                ,                cmap                =                'viridis'                ,                edgecolor                =                'none'                )                ax                .                set_title                (                'surface'                );              

Notation that though the filigree of values for a surface plot needs to exist two-dimensional, it need non exist rectilinear. Here is an case of creating a partial polar grid, which when used with the surface3D plot tin requite the states a slice into the role we're visualizing:

In [ten]:

                                r                =                np                .                linspace                (                0                ,                6                ,                xx                )                theta                =                np                .                linspace                (                -                0.ix                *                np                .                pi                ,                0.8                *                np                .                pi                ,                twoscore                )                r                ,                theta                =                np                .                meshgrid                (                r                ,                theta                )                X                =                r                *                np                .                sin                (                theta                )                Y                =                r                *                np                .                cos                (                theta                )                Z                =                f                (                10                ,                Y                )                ax                =                plt                .                axes                (                project                =                '3d'                )                ax                .                plot_surface                (                X                ,                Y                ,                Z                ,                rstride                =                i                ,                cstride                =                1                ,                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, nosotros instead have a set of random draws?

In [11]:

                            theta              =              2              *              np              .              pi              *              np              .              random              .              random              (              1000              )              r              =              6              *              np              .              random              .              random              (              1000              )              ten              =              np              .              ravel              (              r              *              np              .              sin              (              theta              ))              y              =              np              .              ravel              (              r              *              np              .              cos              (              theta              ))              z              =              f              (              x              ,              y              )            

Nosotros could create a besprinkle plot of the points to become 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 role that will help us in this instance is ax.plot_trisurf, which creates a surface past first finding a set of triangles formed betwixt adjacent points (remember that ten, y, and z here are one-dimensional arrays):

In [13]:

                                ax                =                plt                .                axes                (                projection                =                '3d'                )                ax                .                plot_trisurf                (                x                ,                y                ,                z                ,                cmap                =                'viridis'                ,                edgecolor                =                'none'                );              

The issue is certainly not as make clean as when it is plotted with a filigree, but the flexibility of such a triangulation allows for some really interesting three-dimensional plots. For example, information technology is actually possible to plot a 3-dimensional Möbius strip using this, as we'll come across next.

Example: Visualizing a Möbius strip¶

A Möbius strip is like to a strip of newspaper glued into a loop with a half-twist. Topologically, information technology's quite interesting because despite appearances information technology has but a single side! Here nosotros volition visualize such an object using Matplotlib's three-dimensional tools. The key to creating the Möbius strip is to think about information technology's parametrization: information technology'due south a two-dimensional strip, and then nosotros demand two intrinsic dimensions. Let'southward call them $\theta$, which ranges from $0$ to $2\pi$ around the loop, and $due west$ which ranges from -1 to i across the width of the strip:

In [xiv]:

                            theta              =              np              .              linspace              (              0              ,              two              *              np              .              pi              ,              thirty              )              w              =              np              .              linspace              (              -              0.25              ,              0.25              ,              8              )              w              ,              theta              =              np              .              meshgrid              (              westward              ,              theta              )            

Now from this parametrization, we must make up one's mind the (x, y, z) positions of the embedded strip.

Thinking about it, we might realize that there are two rotations happening: ane is the position of the loop about its center (what we've called $\theta$), while the other is the twisting of the strip most its axis (we'll call this $\phi$). For a Möbius strip, we must have the strip makes half a twist during a total loop, or $\Delta\phi = \Delta\theta/ii$.

Now we use our recollection of trigonometry to derive the three-dimensional embedding. Nosotros'll define $r$, the distance of each point from the centre, and use this to observe the embedded $(ten, y, z)$ coordinates:

In [sixteen]:

                            # radius in ten-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 certain the triangulation is right. The best fashion to do this is to define the triangulation inside the underlying parametrization, and and then allow Matplotlib projection this triangulation into the three-dimensional infinite 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                (                west                ),                np                .                ravel                (                theta                ))                ax                =                plt                .                axes                (                projection                =                '3d'                )                ax                .                plot_trisurf                (                x                ,                y                ,                z                ,                triangles                =                tri                .                triangles                ,                cmap                =                'viridis'                ,                linewidths                =                0.two                );                ax                .                set_xlim                (                -                1                ,                1                );                ax                .                set_ylim                (                -                i                ,                1                );                ax                .                set_zlim                (                -                ane                ,                1                );              

Combining all of these techniques, it is possible to create and brandish a wide variety of three-dimensional objects and patterns in Matplotlib.

robertsonankining.blogspot.com

Source: https://jakevdp.github.io/PythonDataScienceHandbook/04.12-three-dimensional-plotting.html

0 Response to "Python Drawing 3d Graph Plane and Dot"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel