Cara menggunakan plot 3d gaussian python

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

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
7 toolkit, included with the main Matplotlib installation:

In [1]:

from mpl_toolkits import mplot3d

Once this submodule is imported, a three-dimensional axes can be created by passing the keyword

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
8 to any of the normal axes creation routines:

We will begin by plotting a single point in a 3D coordinate space. We will then learn how to customize our plots, and then we’ll move on to more complicated plots like 3D Gaussian surfaces, 3D polygons, etc. Specifically, we will look at the following topics:

 

Table of Contents

1

 

Plot a single point in a 3D space

Let us begin by going through every step necessary to create a 3D plot in Python, with an example of plotting a point in 3D space.

Step 1: Import the libraries

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

The first one is a standard import statement for plotting using matplotlib, which you would see for 2D plotting as well.
The second import of the 

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
4 class is required for enabling 3D projections. It is, otherwise, not used anywhere else.

Note that the second import is required for Matplotlib versions before 3.2.0. For versions 3.2.0 and higher, you can plot 3D plots without importing 

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
5.

Step 2: Create figure and axes

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

Output:

Cara menggunakan plot 3d gaussian python

Here we are first creating a figure of size 4 inches X 4 inches.
We then create a 3-D axis object by calling the 
fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
6 method and specifying the value ‘3d’ to the 
fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
7 parameter.
We will use this axis object ‘ax’ to add any plot to the figure.

 

Note that these two steps will be common in most of the 3D plotting you do in Python using Matplotlib.

Step 3: Plot the point

After we create the axes object, we can use it to create any type of plot we want in the 3D space.
To plot a single point, we will use the 

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
8method, and pass the three coordinates of the point.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()

Output:

Cara menggunakan plot 3d gaussian python

As you can see, a single point has been plotted (in blue) at (2,3,4).

 

Plotting a 3D continuous line

Now that we know how to plot a single point in 3D, we can similarly plot a continuous line passing through a list of 3D coordinates.

We will use the 

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
9 method and pass 3 arrays, one each for the x, y, and z coordinates of the points on the line.

import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()

Output:

Cara menggunakan plot 3d gaussian python

We are generating x, y, and z coordinates for 50 points.
The x and y coordinates are generated using
import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
0 to generate 50 uniformly distributed points between -4π and +4π. The z coordinate is simply the sum of the squares of the corresponding x and y coordinates.

 

Customizing a 3D plot

Let us plot a scatter plot in 3D space and look at how we can customize its appearance in different ways based on our preferences. We will use NumPy random seed so you can generate the same random number as the tutorial.

np.random.seed(42)

xs = np.random.random(100)*10+20

ys = np.random.random(100)*5+7

zs = np.random.random(100)*15+50

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs,ys,zs)

plt.show()

Output:

Cara menggunakan plot 3d gaussian python

Let us now add a title to this plot

Adding a title

We will call the 

import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
1 method of the axes object to add a title to the plot.

ax.set_title("Atom velocity distribution")

plt.show()

Output:

Cara menggunakan plot 3d gaussian python

NOTE that I have not added the preceding code (to create the figure and add scatter plot) here, but you should do it.

Let us now add labels to each axis on the plot.

Adding axes labels

We can set a label for each axis in a 3D plot by calling the methods 

import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
2, 
import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
3 and 
import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
4 on the axes object.

ax.set_xlabel("Atomic mass (dalton)")

ax.set_ylabel("Atomic radius (pm)")

ax.set_zlabel("Atomic velocity (x10⁶ m/s)")

plt.show()

Output:

Cara menggunakan plot 3d gaussian python

Modifying the markers

As we have seen in our previous examples, the marker for each point, by default, is a filled blue circle of constant size.
We can alter the appearance of the markers to make them more expressive.

Let us begin by changing the color and style of the marker

ax.scatter(xs,ys,zs, marker="x", c="red")

plt.show()

Output:

Cara menggunakan plot 3d gaussian python

We have used the parameters 
import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
5 and 
import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
6 to change the style and color of the individual points

Modifying the axes limits and ticks

The range and interval of values on the axes are set by default based on the input values.
We can however alter them to our desired values.

Let us create another scatter plot representing a new set of data points, and then modify its axes range and interval.

np.random.seed(42)

ages = np.random.randint(low = 8, high = 30, size=35)

heights = np.random.randint(130, 195, 35)

weights = np.random.randint(30, 160, 35)

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs = heights, ys = weights, zs = ages)

ax.set_title("Age-wise body weight-height distribution")

ax.set_xlabel("Height (cm)")

ax.set_ylabel("Weight (kg)")

ax.set_zlabel("Age (years)")

plt.show()

Output:

Cara menggunakan plot 3d gaussian python

We have plotted data of 3 variables, namely, height, weight and age on the 3 axes.
As you can see, the limits on the X, Y, and Z axes have been assigned automatically based on the input data.

Let us modify the minimum and maximum limit on each axis, by calling the 

import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
7, 
import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
8, and 
import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
9 methods.

ax.set_xlim(100,200)

ax.set_ylim(20,160)

ax.set_zlim(5,35)

plt.show()

Output:

Cara menggunakan plot 3d gaussian python

The limits for the three axes have been modified based on the min and max values we passed to the respective methods.
We can also modify the individual ticks for each axis. Currently, the X-axis ticks are [100,120,140,160,180,200].
Let us update this to [100,125,150,175,200]

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')
0

Output:

Cara menggunakan plot 3d gaussian python

Similarly, we can update the Y and Z ticks using the 
np.random.seed(42)

xs = np.random.random(100)*10+20

ys = np.random.random(100)*5+7

zs = np.random.random(100)*15+50

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs,ys,zs)

plt.show()
0 and 
np.random.seed(42)

xs = np.random.random(100)*10+20

ys = np.random.random(100)*5+7

zs = np.random.random(100)*15+50

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs,ys,zs)

plt.show()
1 methods.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')
1

Output:

Cara menggunakan plot 3d gaussian python

Change the size of the plot

If we want our plots to be bigger or smaller than the default size, we can easily set the size of the plot either when initializing the figure – using the 

np.random.seed(42)

xs = np.random.random(100)*10+20

ys = np.random.random(100)*5+7

zs = np.random.random(100)*15+50

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs,ys,zs)

plt.show()
2 parameter of the 
np.random.seed(42)

xs = np.random.random(100)*10+20

ys = np.random.random(100)*5+7

zs = np.random.random(100)*15+50

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs,ys,zs)

plt.show()
3 method,
or we can update the size of an existing plot by calling the 
np.random.seed(42)

xs = np.random.random(100)*10+20

ys = np.random.random(100)*5+7

zs = np.random.random(100)*15+50

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs,ys,zs)

plt.show()
4 method on the figure object.
In both approaches, we must specify the width and height of the plot in inches.

Since we have seen the  earlier, let us look at the second approach now i.e modifying the size of an existing plot.
We will change the size of our scatter plot to 6×6 inches.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')
2

Output:

Cara menggunakan plot 3d gaussian python

The size of our scatter plot has been increased compared to its previous default size.

Turn off/on gridlines

All the plots that we have plotted so far have gridlines on them by default.
We can change this by calling the 

np.random.seed(42)

xs = np.random.random(100)*10+20

ys = np.random.random(100)*5+7

zs = np.random.random(100)*15+50

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs,ys,zs)

plt.show()
5 method of the axes object, and pass the value ‘False.’
If we want the gridlines back again, we can call the same method with the parameter ‘True.’.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')
3

Output:

Cara menggunakan plot 3d gaussian python

Set 3D plot colors based on class

Let us suppose that the individuals represented by our scatter plot were further divided into two or more categories.
We can represent this information by plotting the individuals of each category with a different color.
For instance, let us divide our data into ‘Male’ and ‘Female’ categories.
We will create a new array of the same size as the number of data points, and assign the values 0 for ‘Male’ and 1 for the ‘Female’ category.
We will then pass this array to the color parameter 

import numpy as np

x = np.linspace(−4*np.pi,4*np.pi,50)

y = np.linspace(−4*np.pi,4*np.pi,50)

z = x**2 + y**2

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.plot(x,y,z)

plt.show()
6 when creating the scatter plot.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')
4

Output:

Cara menggunakan plot 3d gaussian python

The plot now shows each of the two categories with a different color.
But how would we know which color corresponds to which category?

We can add a ‘colorbar’ to solve this problem.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')
5

Output:

Cara menggunakan plot 3d gaussian python

Putting legends

Often we have more than 1 set of data that we want to plot on the same figure.
In such a situation, we must assign labels to each plot and add a legend to the figure to distinguish the different plots from each other.

For eg, let us suppose that our age-height-weight data were collected from 3 states of the United States, namely, Florida, Georgia and California.
We want to plot scatter plots for the 3 states and add a legend to distinguish them from each other.

Let us create the 3 plots in a for-loop and assign a different label to them each time.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')
6

Output:

Cara menggunakan plot 3d gaussian python

Plot markers of varying size

In the scatter plots that we have seen so far, all the point markers have been of constant sizes.

We can alter the size of markers by passing custom values to the parameter 

np.random.seed(42)

xs = np.random.random(100)*10+20

ys = np.random.random(100)*5+7

zs = np.random.random(100)*15+50

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs,ys,zs)

plt.show()
7 of the scatter plot.
We can either pass a single number to set all the markers to a new fixed size, or we can provide an array of values, where each value represents the size of one marker.

In our example, we will calculate a new variable called ‘bmi’ from the heights and weights of individuals and make the sizes of individual markers proportional to their BMI values.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')
7

Output:

Cara menggunakan plot 3d gaussian python

The greater the sizes of markers in this plot, the higher are the BMI’s of those individuals, and vice-versa.

Plotting a Gaussian distribution

You may be aware of a univariate Gaussian distribution plotted on a 2D plane, popularly known as the ‘bell-shaped curve.’

Cara menggunakan plot 3d gaussian python

source: https://en.wikipedia.org/wiki/File:Normal_Distribution_PDF.svg

We can also plot a Gaussian distribution in a 3D space, using the multivariate normal distribution.
We must define the variables X and Y and plot a probability distribution of them together.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')
8

Output:

Cara menggunakan plot 3d gaussian python

Using the 
np.random.seed(42)

xs = np.random.random(100)*10+20

ys = np.random.random(100)*5+7

zs = np.random.random(100)*15+50

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs,ys,zs)

plt.show()
8 method, we can create similar surfaces in a 3D space.

Plotting a 3D Polygon

We can also plot polygons with 3-dimensional vertices in Python.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')
9

Output:

Cara menggunakan plot 3d gaussian python

Rotate a 3D plot with the mouse

To create an interactive plot in a Jupyter Notebook, you should run the
magic command 

np.random.seed(42)

xs = np.random.random(100)*10+20

ys = np.random.random(100)*5+7

zs = np.random.random(100)*15+50

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs,ys,zs)

plt.show()
9 at the beginning of the notebook.

This enables us to interact with the 3D plots, by zooming in and out of the plot, as well as rotating them in any direction.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
0

Output:

Cara menggunakan plot 3d gaussian python

Plot two different 3D distributions

We can add two different 3D plots to the same figure, with the help of the 

ax.set_title("Atom velocity distribution")

plt.show()
0 method.
The 3-digit number we supply to the method indicates the number of rows and columns in the grid and the position of the current plot in the grid.
The first two digits indicate the total number of rows and columns we need to divide the figure in.
The last digit indicates the position of the subplot in the grid.

For example, if we pass the value 223 to the 

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
6 method, we are referring to the 3rd plot in the 2×2 grid (considering row-first ordering).

Let us now look at an example where we plot two different distributions on a single plot.

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
1

Output:

Cara menggunakan plot 3d gaussian python

We can plot as many subplots as we want in this way, as long as we fit them right in the grid.

Output Python 3D plot to HTML

If we want to embed a 3D plot figure to an HTML page, without first saving it as an image file,
we can do so by encoding the figure into ‘base64’ and then inserting it at the correct position in an HTML 

ax.set_title("Atom velocity distribution")

plt.show()
2 tag

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
2

We can now write this HTML code string to an HTML file, which we can then view in a browser

fig = plt.figure(figsize=(4,4))

ax = fig.add_subplot(111, projection='3d')

ax.scatter(2,3,4) # plot the point (2,3,4) on the figure

plt.show()
3

Output:

Cara menggunakan plot 3d gaussian python

Conclusion

In this tutorial, we learned how to plot 3D plots in Python using the matplotlib library.
We began by plotting a point in the 3D coordinate space, and then plotted 3D curves and scatter plots.

Then we learned various ways of customizing a 3D plot in Python, such as adding a title, legends, axes labels to the plot, resizing the plot, switching on/off the gridlines on the plot, modifying the axes ticks, etc.
We also learned how to vary the size and color of the markers based on the data point category.

After that, we learned how to plot surfaces in a 3D space. We plotted a Gaussian distribution and a 3D polygon in Python.

We then saw how we can interact with a Python 3D plot in a Jupyter notebook.

Finally, we learned how to plot multiple subplots on the same figure, and how to output a figure into an HTML code.