draw line between two 3d points matplotlib

Matplotlib was initially designed with just ii-dimensional plotting in listen. Effectually the time of the 1.0 release, some three-dimensional plotting utilities were built on top of Matplotlib'south two-dimensional display, and the result is a convenient (if somewhat limited) set of tools for three-dimensional information visualization. iii-dimensional plots are enabled by importing the mplot3d toolkit, included with the primary Matplotlib installation:

In [1]:

                            from              mpl_toolkits              import              mplot3d            

Once this submodule is imported, a 3-dimensional axes tin be created by passing the keyword projection='3d' to any of the normal axes cosmos routines:

In [2]:

                            %              matplotlib              inline              import              numpy              every bit              np              import              matplotlib.pyplot              equally              plt            

In [3]:

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

With this three-dimensional axes enabled, nosotros 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; call up that to apply interactive figures, you lot can apply %matplotlib notebook rather than %matplotlib inline when running this lawmaking.

Three-dimensional Points and Lines¶

The most basic three-dimensional plot is a line or collection of besprinkle plot created from sets of (10, y, z) triples. In analogy with the more common two-dimensional plots discussed before, these tin can be created using the ax.plot3D and ax.scatter3D functions. The call signature for these is nearly identical to that of their two-dimensional counterparts, so you tin can refer to Simple Line Plots and Simple Scatter Plots for more than information on controlling the output. Here we'll plot a trigonometric spiral, along with some points drawn randomly near 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                ,                'grey'                )                # Information for three-dimensional scattered points                zdata                =                15                *                np                .                random                .                random                (                100                )                xdata                =                np                .                sin                (                zdata                )                +                0.one                *                np                .                random                .                randn                (                100                )                ydata                =                np                .                cos                (                zdata                )                +                0.i                *                np                .                random                .                randn                (                100                )                ax                .                scatter3D                (                xdata                ,                ydata                ,                zdata                ,                c                =                zdata                ,                cmap                =                'Greens'                );              

Notice that by default, the besprinkle points have their transparency adapted to requite a sense of depth on the page. While the three-dimensional upshot is sometimes difficult to come across within a static paradigm, an interactive view can lead to some nice intuition nearly the layout of the points.

Three-dimensional Profile Plots¶

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

In [five]:

                            def              f              (              x              ,              y              ):              return              np              .              sin              (              np              .              sqrt              (              x              **              2              +              y              **              2              ))              x              =              np              .              linspace              (              -              6              ,              6              ,              thirty              )              y              =              np              .              linspace              (              -              half dozen              ,              half dozen              ,              30              )              Ten              ,              Y              =              np              .              meshgrid              (              x              ,              y              )              Z              =              f              (              10              ,              Y              )            

In [half dozen]:

                                fig                =                plt                .                figure                ()                ax                =                plt                .                axes                (                project                =                '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 case we can apply the view_init method to set the elevation and azimuthal angles. In the post-obit example, we'll use an elevation of sixty degrees (that is, lx degrees in a higher place the x-y plane) and an azimuth of 35 degrees (that is, rotated 35 degrees counter-clockwise about the z-axis):

Out[7]:

Over again, annotation that this blazon of rotation can exist accomplished interactively by clicking and dragging when using 1 of Matplotlib'south interactive backends.

Wireframes and Surface Plots¶

Two other types of three-dimensional plots that work on gridded information are wireframes and surface plots. These take a grid of values and project it onto the specified three-dimensional surface, and can make the resulting 3-dimensional forms quite easy to visualize. Hither's an example of using a wireframe:

In [eight]:

                                fig                =                plt                .                effigy                ()                ax                =                plt                .                axes                (                project                =                '3d'                )                ax                .                plot_wireframe                (                10                ,                Y                ,                Z                ,                colour                =                'blackness'                )                ax                .                set_title                (                'wireframe'                );              

A surface plot is like a wireframe plot, only each confront 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 [ix]:

                                ax                =                plt                .                axes                (                projection                =                '3d'                )                ax                .                plot_surface                (                X                ,                Y                ,                Z                ,                rstride                =                ane                ,                cstride                =                1                ,                cmap                =                'viridis'                ,                edgecolor                =                'none'                )                ax                .                set_title                (                'surface'                );              

Annotation that though the grid of values for a surface plot needs to exist ii-dimensional, information technology need non be rectilinear. Here is an example of creating a fractional polar grid, which when used with the surface3D plot tin can give united states of america a slice into the function nosotros're visualizing:

In [10]:

                                r                =                np                .                linspace                (                0                ,                6                ,                20                )                theta                =                np                .                linspace                (                -                0.ix                *                np                .                pi                ,                0.8                *                np                .                pi                ,                40                )                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                (                X                ,                Y                ,                Z                ,                rstride                =                1                ,                cstride                =                one                ,                cmap                =                'viridis'                ,                edgecolor                =                'none'                );              

Surface Triangulations¶

For some applications, the evenly sampled grids required by the above routines is overly restrictive and inconvenient. In these situations, the triangulation-based plots can be very useful. What if rather than an fifty-fifty depict from a Cartesian or a polar grid, we instead have a set of random draws?

In [xi]:

                            theta              =              2              *              np              .              pi              *              np              .              random              .              random              (              grand              )              r              =              vi              *              np              .              random              .              random              (              1000              )              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 go an thought of the surface we're sampling from:

In [12]:

                                ax                =                plt                .                axes                (                project                =                '3d'                )                ax                .                besprinkle                (                10                ,                y                ,                z                ,                c                =                z                ,                cmap                =                'viridis'                ,                linewidth                =                0.5                );              

This leaves a lot to be desired. The function that will help us in this example is ax.plot_trisurf, which creates a surface by first finding a gear up of triangles formed betwixt adjacent points (remember that ten, y, and z hither are one-dimensional arrays):

In [13]:

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

The result 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 three-dimensional plots. For instance, information technology is actually possible to plot a three-dimensional Möbius strip using this, as nosotros'll see next.

Instance: 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, information technology's quite interesting because despite appearances it has only a single side! Here we volition visualize such an object using Matplotlib'southward three-dimensional tools. The fundamental to creating the Möbius strip is to think about information technology's parametrization: information technology's a 2-dimensional strip, so we need two intrinsic dimensions. Permit's call them $\theta$, which ranges from $0$ to $2\pi$ around the loop, and $w$ which ranges from -1 to 1 across the width of the strip:

In [xiv]:

                            theta              =              np              .              linspace              (              0              ,              2              *              np              .              pi              ,              30              )              due west              =              np              .              linspace              (              -              0.25              ,              0.25              ,              8              )              w              ,              theta              =              np              .              meshgrid              (              w              ,              theta              )            

Now from this parametrization, nosotros must determine the (x, y, z) positions of the embedded strip.

Thinking nearly information technology, we might realize that there are two rotations happening: ane is the position of the loop about its eye (what we've called $\theta$), while the other is the twisting of the strip about its axis (we'll telephone 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/ii$.

Now we employ our recollection of trigonometry to derive the three-dimensional embedding. We'll ascertain $r$, the distance of each point from the center, and use this to find the embedded $(x, y, z)$ coordinates:

In [16]:

                            # radius in x-y plane              r              =              1              +              west              *              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 best way to do this is to define the triangulation within the underlying parametrization, and then let 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                (                west                ),                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                (                -                1                ,                1                );                ax                .                set_ylim                (                -                1                ,                1                );                ax                .                set_zlim                (                -                ane                ,                1                );              

Combining all of these techniques, it is possible to create and display a broad diversity of iii-dimensional objects and patterns in Matplotlib.

comesposely.blogspot.com

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

0 Response to "draw line between two 3d points matplotlib"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel