Skip to content Skip to sidebar Skip to footer

python draw histogram in 3d

Matplotlib was initially designed with but two-dimensional plotting in listen. Around the time of the 1.0 release, some three-dimensional plotting utilities were built on height of Matplotlib's ii-dimensional display, and the result 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 main Matplotlib installation:

In [1]:

                            from              mpl_toolkits              import              mplot3d            

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

In [ii]:

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

In [three]:

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

With this three-dimensional axes enabled, we can now plot a variety of iii-dimensional plot types. Iii-dimensional plotting is one of the functionalities that benefits immensely from viewing figures interactively rather than statically in the notebook; think that to apply interactive figures, you tin 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 scatter plot created from sets of (x, y, z) triples. In analogy with the more common two-dimensional plots discussed before, these can be created using the ax.plot3D and ax.scatter3D functions. The telephone call signature for these is almost identical to that of their 2-dimensional counterparts, so y'all can refer to Simple Line Plots and Elementary Scatter Plots for more data on controlling the output. Hither 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                ,                m                )                xline                =                np                .                sin                (                zline                )                yline                =                np                .                cos                (                zline                )                ax                .                plot3D                (                xline                ,                yline                ,                zline                ,                'grayness'                )                # Data for three-dimensional scattered points                zdata                =                xv                *                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 besprinkle points have their transparency adapted to give a sense of depth on the page. While the 3-dimensional result is sometimes difficult to see within a static image, an interactive view can lead to some prissy intuition near the layout of the points.

Three-dimensional Profile Plots¶

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

In [5]:

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

In [6]:

                                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 instance we tin utilize the view_init method to set up the elevation and azimuthal angles. In the following example, we'll utilise an elevation 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 virtually the z-axis):

Out[7]:

Once again, note that this blazon of rotation tin be accomplished interactively by clicking and dragging when using one of Matplotlib'south interactive backends.

Wireframes and Surface Plots¶

Ii other types of 3-dimensional plots that work on gridded information are wireframes and surface plots. These have a filigree of values and project it onto the specified iii-dimensional surface, and can make the resulting three-dimensional forms quite easy to visualize. Here's an case of using a wireframe:

In [8]:

                                fig                =                plt                .                effigy                ()                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 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                =                i                ,                cstride                =                1                ,                cmap                =                'viridis'                ,                edgecolor                =                'none'                )                ax                .                set_title                (                'surface'                );              

Note that though the grid of values for a surface plot needs to be two-dimensional, it demand non be rectilinear. Here is an example of creating a partial polar grid, which when used with the surface3D plot can requite us a slice into the function we're visualizing:

In [x]:

                                r                =                np                .                linspace                (                0                ,                vi                ,                20                )                theta                =                np                .                linspace                (                -                0.9                *                np                .                pi                ,                0.eight                *                np                .                pi                ,                forty                )                r                ,                theta                =                np                .                meshgrid                (                r                ,                theta                )                X                =                r                *                np                .                sin                (                theta                )                Y                =                r                *                np                .                cos                (                theta                )                Z                =                f                (                Ten                ,                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 have a set of random draws?

In [11]:

                            theta              =              2              *              np              .              pi              *              np              .              random              .              random              (              1000              )              r              =              half dozen              *              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 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.5                );              

This leaves a lot to exist desired. The function that volition help us in this instance is ax.plot_trisurf, which creates a surface past showtime finding a set of triangles formed between adjacent points (remember that x, y, and z here are ane-dimensional arrays):

In [xiii]:

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

The event is certainly non every bit clean as when it is plotted with a grid, but the flexibility of such a triangulation allows for some really interesting three-dimensional plots. For example, it is actually possible to plot a three-dimensional Möbius strip using this, as nosotros'll see 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 simply a single side! Here we will visualize such an object using Matplotlib's three-dimensional tools. The central to creating the Möbius strip is to think about it's parametrization: information technology's a two-dimensional strip, and then we demand two intrinsic dimensions. Let'due south call them $\theta$, which ranges from $0$ to $2\pi$ around the loop, and $w$ which ranges from -one to 1 beyond the width of the strip:

In [14]:

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

At present from this parametrization, we must determine the (x, y, z) positions of the embedded strip.

Thinking nearly it, we might realize that there are two rotations happening: one is the position of the loop about its heart (what we've chosen $\theta$), while the other is the twisting of the strip well-nigh its axis (we'll call this $\phi$). For a Möbius strip, we must take 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 iii-dimensional embedding. We'll define $r$, the distance of each point from the center, and employ this to find the embedded $(x, y, z)$ coordinates:

In [xvi]:

                            # radius in x-y aeroplane              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, we must make sure the triangulation is correct. The all-time fashion to practise this is to define the triangulation inside the underlying parametrization, so allow Matplotlib project 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                (                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                (                -                1                ,                ane                );                ax                .                set_ylim                (                -                1                ,                1                );                ax                .                set_zlim                (                -                1                ,                one                );              

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

lewiswhileme.blogspot.com

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

Post a Comment for "python draw histogram in 3d"