Matplotlib 3D scatter

In this Python tutorial, we will discuss Matplotlib 3D scatter in python. Here we will cover different examples related to the 3D scatter using matplotlib. And we will also cover the following topics:

  • Matplotlib 3D scatter plot
  • Matplotlib 3D scatter plot example
  • Matplotlib 3D scatter color
  • Matplotlib 3D scatter with colorbar
  • Matplotlib 3D scatter marker size
  • Matplotlib 3D scatter label
  • Matplotlib 3D scatter legend
  • Matplotlib 3D scatter plot color by value
  • Matplotlib 3D scatter rotate
  • Matplotlib 3D scatter change view angle
  • Matplotlib 3D scatter title
  • Matplotlib 3D scatter text
  • Matplotlib 3D scatter with line
  • Matplotlib 3D scatter with surface
  • Matplotlib 3D sactter transparency
  • Matplotlib 3D sactter depthshade
  • Matplotlib 3D scatter axis limits
  • Matplotlib 3D scatter axis ticks
  • Matplotlib 3D scatter size
  • Matplotlib 3D scatter grid
  • Matplotlib 3D scatter subplot
  • Matplotlib 3D scatter save
  • Matplotlib 3D scatter background color
  • Matplotlib 3D scatter numpy array
  • Matplotlib 3D scatter marker color
  • Matplotlib 3D scatter zlim
  • Matplotlib 3D scatter z label
  • Matplotlib 3D scatter xlim
  • Matplotlib 3D scatter zoom
  • Matplotlib 3D scatter origin
  • Matplotlib 3D scatter log scale
  • Matplotlib 3D scatter dataframe
  • Matplotlib 3D scatter animation

Matplotlib 3D scatter plot

In this section, we learn about how to plot a 3D scatter plot in matplotlib in Python. Before starting the topic, firstly we have to understand what does 3D and scatter plot means:

3D stands for Three-Dimensional. “

Any object in the real world having Three-Dimensions is known as 3D object. Having Three-Dimensions means height, width and depth.

Scatter plot is a graph in which the values of variables are plotted along the axes, by using the points.

A 3D Scatter Plot is a mathematical diagram, used to display the properties of data as three variables using the cartesian coordinates. In matplotlib to create a 3D scatter plot, we have to import the mplot3d toolkit.

The scatter3D() function of the matplotlib library, which accepts X, Y, and Z data sets, is used to build a 3D scatter plot.

The following steps are used to draw a 3D scatter plot are outlined below:

  • Defining Libraries: Import the most important library which is required to plot 3D graphs mplot3d toolkit and also import other libraries which are required for data creation and manipulation numpy and pandas, for data visualization: pyplot from matplotlib.
  • Define X and Y: Define the data coordinates values used for the x-axis and y-axis data plotting.
  • Plot 3D scatter plot: By using scatter3D() method of the matplotlib library we can draw 3D scatter plot.
  • Visulaize a Plot: By using show() method user can generate a plot on their screen.

Matplotlib 3D scatter plot example

# Import Library

from mpl_toolkits import mplot3d

# Function to create 3D scatter plot

matplotlib.axes.Axis.scatter3D(x, y, z)

Here x, y, and z represent the Three-Dimensions of the plot.

Let’s see an example to understand the concept more clearly:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

x = np.arange(0, 20, 0.2)
y = np.sin(x)
z = np.cos(x)
 
# Create Figure

fig = plt.figure(figsize = (10, 7))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x, y, z)
 
# Show plot

plt.show()
  • In the above example, we import mplot3d toolkits, numpy, and pyplot libraries.
  • Next, we define data using arange(), sin(), and cos() method.
  • plt.figure() method is used to set figure size here we pass figsize as a parameter and plt.axes() method is used to set axes and here we pass projection as a parameter.
  • ax.scatter3D() method is used to create 3D scatter plot, here we pass x, y, and z as parameter.
  • plt.show() method is used to generate graph on user screen.
matplotlib 3D scatter plot example
plt.scatter3D()

Read: Matplotlib plot_date

Matplotlib 3D scatter color

In this section, we are going to learn how to change the color of the 3D scatter plot.

The syntax to change the color is given below:

matplotlib.axes.Axis.scatter3D(x, y, z, color=None)
  • x: specify x-coordinates of the axes.
  • y: specify y-coordinates of the axes.
  • z: specify z-coodinates of the axes.
  • color: specify color of the scatter.

Let’s see an example where we change the color of the 3D scatters:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

x = [2, 4, 6, 8, 10]
y = [5, 10, 15, 20, 25]
z = [3, 6, 9, 12, 15]
 
# Create Figure

fig = plt.figure(figsize = (10, 7))
ax = plt.axes(projection ="3d")
 
# Create Plot and change color

ax.scatter3D(x, y, z, color='red')
 
# Show plot

plt.show()
  • In the above example, we import mplot3d toolkits, numpy, and pyplot libraries.
  • Next, we define data.
  • plt.figure() method is used to set figure size here we pass figsize as a parameter and plt.axes() method is used to set axes and here we pass projection as a parameter.
  • ax.scatter3D() method is used to create 3D scatter plot, here we pass x, y, z and color as parameter. Here color change the color of the plot.
  • plt.show() method is used to generate graph on user screen.
matplotlib 3d scatter color
ax.scatter3D(color=None)

Read: Matplotlib dashed line

Matplotlib 3D scatter with colorbar

Here we draw a 3D scatter plot with a color bar. By using the get_cmap() method we create a colormap.

The syntax to plot color bar:

# Create scatter Plot

matplotlib.axis.Axis.scatter3D(x, y, z, cmap)

# To Plot colorbar

matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, label, ticks)

Here cmap specify the color map.

Example:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Dataset

x = np.random.randint(100,size=(80))
y = np.random.randint(150, size=(80))
z = np.random.randint(200, size=(80))
 
# Creating figure

fig = plt.figure(figsize = (16, 9))
ax = plt.axes(projection ="3d")
  
# Creat color map

color_map = plt.get_cmap('spring')
 
# Create scatter plot and colorbar

scatter_plot = ax.scatter3D(x, y, z,
                            c=(x+y+z),
                            cmap = color_map)
 
plt.colorbar(scatter_plot)
 
# Show plot

plt.show()
  • In the above example, we import mplot3d toolkits, numpy, and pyplot libraries.
  • Next, we define data using random.randint() method.
  • plt.axes() method is used to set axes and here we pass projection as a parameter.
  • plt.get_cmap() method is used to create color map of the specific color.
  • ax.scatter3D() method is used to create 3D scatter plot, here we pass x, y, z and cmap as parameter. Here cmap define the color map.
  • fig.colorbar() method is used to add colorbar to a plot that indicates the color scale.
matplotlib 3d scatter with colorbar
plt.colorbar()

Read: Matplotlib scatter marker

Matplotlib 3D scatter marker size

Here we are going to learn how we can change the marker and marker size of the 3D scatter plot in matplotlib.

The syntax to change the marker size is given below:

matplotlib.axis.Axis.scatter(x, y, z, s=None, marker=None)

The parameters used above are:

  • x: specify the data position on x-axis.
  • y: specify the data position on y-axis.
  • s: specify the marker size in points**2.
  • marker: specify marker style.

Let’s see an example where we change the scatter marker and its size:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

x = np.arange(0, 20, 0.2)
y = np.sin(x)
z = np.cos(x)
 
# Create Figure

fig = plt.figure(figsize = (8,6))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x, y, z, marker= '>', s=50)
 
# Show plot

plt.show()

Here we use an ax.scatter() method to create a scatter plot and we pass marker and s as parameters to change marker style and marker size respectively. We set the marker size to 50.

matplotlib 3d scatter marker size
ax.scatter3D(marker, s=None)

Read: Matplotlib change background color

Matplotlib 3D scatter label

Here we are going to learn how to add labels to the 3D scatter graph.

The syntax to add label is given below:

# To add x-axis label

ax.set_xlabel()

# To add y-axis label

ax.set_ylabel()

# To add z-axis label

ax.set_zlabel()

Example:

Here we use ax.scatter3D() function to plot 3D scatter plot.

ax.set_xlabel(), ax.set_ylabel(), and ax.set_zlabel() function is used to add labels to the plot. We pass X-axis, Y-axis, and Z-axis to respective functions.

Code:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

z = [3, 6, 9, 12, 15]
x = [2, 4, 6, 8, 10]
y = [5, 10, 15, 20, 25]

 
# Create Figure

fig = plt.figure(figsize = (10, 7))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x, y, z, color='red')

# Add axis

ax.set_xlabel('X-axis', fontweight ='bold')
ax.set_ylabel('Y-axis', fontweight ='bold')
ax.set_zlabel('Z-axis', fontweight ='bold')
 
# Show plot

plt.show()

Output:

Matplotlib 3d scatter label
” 3D Scatter Plot with Labels “

Also, check: Matplotlib rotate tick labels

Matplotlib 3D scatter legend

Here we learn how to add a legend to the 3D scatter plot. By using the legend() function we can easily add.

Example:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

x = np.arange(0, 20, 0.2)
y =  np.sin(x)
z1 = np.cos(x)
z2 = np.exp(8)
 
# Create Figure

fig = plt.figure(figsize = (10, 7))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x, y, z1, marker='<', s=20, label='Triangle')
ax.scatter3D(x, y, z2, marker='o', s=20, label='Circle' )

# Add legend

ax.legend(loc=1)
 
# Show plot

plt.show()
  • Here we plot 3d scatter graph between x, y and z1 axes and x, y , and z2 axes.
  • By using the ax.sactter3D() method we plot 3D sactter graph and we pass label as a parameter.
  • ax.legend() method is use to add legend to the plot.
matplotlib 3d scatter legend
ax.legend()

Read: Matplotlib remove tick labels

Matplotlib 3D scatter plot color by value

Here we are going to learn how we can plot a 3D scatter plot for different data and color by value.

Let’s see an example to understand the concept more clearly:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Define Data

x1 = np.random.randint(450,size=(80))
y1 = np.random.randint(260, size=(80))
z1 = np.random.randint(490, size=(80))

x2 = np.random.randint(100,size=(50))
y2 = np.random.randint(150, size=(50))
z2 = np.random.randint(200, size=(50))

x3 = [3, 6, 9, 12, 15]
y3 = [2, 4, 6, 8, 10]
z3 = [5, 10, 15, 20, 25]

# Create Figure

fig = plt.figure(figsize = (8,6))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x1, y1, z1, s=50, color='red')
ax.scatter3D(x2, y2, z2, s=50, color='yellow')
ax.scatter3D(x3, y3, z3, s=50, color='pink')

# Show plot

plt.show()
  • Here we plot a 3D scatter plot using three different data sets.
  • Then by using the ax.scatter3D() function we plot scatter plots for different datasets.
  • Bypassing color as a parameter we color the scatter plot by values.
matplotlib 3d scatter plot color by value
” 3D Scatter Plot Color by Value “

Also, read: Matplotlib plot error bars

Matplotlib 3D scatter rotate

Here we are going to learn how we can rotate the 3D scatter plot by moving the mouse only.

To turn on the interactivity or to rotate 3D scatter plot using mouse use this line in your code:

%matplotlib notebook

Let’s see an example:

# Interactive Mode

%matplotlib notebook

# Import Library

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

# Create Plot

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

# Define Data

X = [1,2,3,4,5,6,7,8,9,10]
Y = [5,6,2,3,13,4,1,2,4,8]
Z = [2,3,3,3,5,7,9,11,9,10]

# Plot 3D scatter Plot

ax.scatter(X,Y,Z, c='r', marker='o')

# Define Label

ax.set_xlabel('x axis')
ax.set_ylabel('y axis')
ax.set_zlabel('z axis')

# Display

plt.show()
  • In the above example, we enable the Interactive Mode from the backend.
  • Next, we import libraries mplot3D and pyplot.
  • Then we create a plot and define data.
  • ax.scatter3D() method is used to plot 3D scatter graph.
  • set_xlabel(), set_ylabel, and set_zlabel() method is used to add labels to the plot.
  • plt.show() method is used to display plot the user screen.
matplotlib 3d scatter rotate
” Original 3D Scatter Plot”
matplotlib rotate 3d scatter
” Rotation of 3D scatter by mouse “
rotate 3d scatter plot
” Rotation using Mouse “

Read: Add text to plot matplotlib in Python

Matplotlib 3D scatter change view angle

Here we can learn how we can view 3D scatter graphs from different angles. By using the view_init() method we can change the view angle.

The syntax to change view angle is given below:

matplotlib.axis.Axis.view_init(elev,azim)

The parameter used above is given below:

  • elev: specify the elevation angle in the z plane.
  • azim: specify the azimuth angle in the x,y plane.

Let’s see an example where we change the view angle:

# Import Library

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Plotting 3D axis figures

fig = plt.figure(figsize = (8,8))
ax = plt.axes(projection = '3d')
  
# Define Data

z = np.linspace(0, 20, 500)
x = np.sin(z)
y = np.cos(z)
ax.plot3D(x, y, z, 'green')

# Change view angle

ax.view_init(50, 20)

# Display

plt.show()
  • In this example, we import mplot3d, numpy, and pyplot library.
  • Then we plot the 3D axis figure by using plt.figure() and plt.axes() method and we also pass figsize and projection as a parameter respectively.
  • After this, we create a dataset for the three axes.
  • ax.scatter3D() method is used to plot 3D scatter graph.
  • view_init() method is used to change the view angle.

Output: Plot without rotation.

3d scatter change view angle matplotlib
” 3D scatter plot without rotation “

Output: Plot a 3D scatter graph with an elevated angle of 50 degrees and a horizontal angle of 20 degrees.

3d scatter plot change view angle matplotlib
” 3D Scatter Plot with rotation “

Read: Matplotlib save as png

Matplotlib 3D scatter title

Here we are going to learn how to plot 3D scatter plot with the title.

The syntax to add a title to the 3D scatter plot:

matplotlib.pyplot.title()

Let’s see an example:

# Import Library

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Plotting 3D axis figures

fig = plt.figure(figsize = (6,4))
ax = plt.axes(projection = '3d')
  
# Define Data

z = np.linspace(0,15,150)
x = np.sin(z)
y = np.cos(z)

# Plot 3D scatter 

ax.scatter3D(x, y, z, color='m')

# Add Title

plt.title('3D SCATTER PLOT', fontweight='bold', size=20)

# Display

plt.show()
  • In the above example, we import mplot3d, numpy, and pyplot library.
  • Next, we define data using linespace(), sin(), and cos() method.
  • ax.scatter3D() method is used to draw scatter plots.
  • plt.title() method is used to add the title to the 3D scatter plot.
matplotlib 3d scatter title
plt.title()

Read: Matplotlib bar chart labels

Matplotlib 3D scatter text

Here we are going to learn how to add text to the 3D scatter plot. By using the ax.text() method we can do it.

Let’s see an example where we add text in 3D scatter plot at a fixed position:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

z = [3, 6, 9, 12, 15]
x = [2, 4, 6, 8, 10]
y = [5, 10, 15, 20, 25]

# Create Figure

fig = plt.figure(figsize = (10, 7))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x, y, z)

# Add axis

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

# Add Text

ax.text3D(6, 4, 10,"Point 2")
 
# Show plot

plt.show()
  • Here we first define the data for plotting, then by using the ax.scatter() function we plot 3D scatter graph.
  • ax.text() method is used to add text to the plot at a fixed location. We pass three locations (x, y, z axes) where text is placed and the text which we want to add.
matplotlib 3d scatter text
ax.text()

Read: Matplotlib default figure size

Matplotlib 3D scatter with line

Here we are going to learn how we can plot a 3D scatter graph with line. To connect scatter points, we use the plot3D() method with x, y, and z data points.

Let’s see an example where we plot a 3D scatter graph with the line:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

z = [3, 6, 9, 12, 15]
x = [2, 4, 6, 8, 10]
y = [5, 10, 15, 20, 25]
 
# Create Figure

fig = plt.figure(figsize = (10, 7))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x, y, z, color='red')

# Add line

ax.plot3D(x,y,z)

# Add axis

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

# Show plot

plt.show()
  • By using figure() function we create a new figure and add an axes to the current figure as a subplot.
  • Define the data points x, y, and z.
  • ax.scatter3D() function is use to plot scatter 3D plot.
  • ax.plot3D() function is used to connect the points with x, y, and z data points.
  • plt.show() method is use to display the figure.
matplotlib 3d scatter with line
ax.plot3D()

Read: Matplotlib savefig blank image

Matplotlib 3D scatter with surface

Here we are going to learn how to plot a 3D scatter graph with a surface. Firstly, we have to understand what is Surface Plot:

A Surface Plot is a representation of a three-dimensional dataset. It represents the relationship between two variables X and Z and the dependent variable Y.

The ax.plot_surface() function is used to create surface plots.

The syntax of the given method is given below:

matplotlib.axis.Axis.plot_surface(X, Y, Z)

Where X, Y, and Z are three-dimensional data coordinates points.

Let’s see an example of 3D scatter with the surface:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Define Function

def function_z(x,y):
    return 100 - (x**2 + y**2)

# Define Data

x_val = np.linspace(-3, 3, 30)
y_val = np.linspace(-3, 3, 30)

X, Y = np.meshgrid(x_val, y_val)

# Call function

z = function_z(X, Y)

# Create figure

fig = plt.figure(figsize =(10,6))
ax = plt.axes(projection='3d')

# Create surface plot

ax.plot_surface(X, Y, z, color='yellow');

# Display

plt.show()
  • In the above example, firstly we import matplotlib.pyplot, numpy, and mplot3D.
  • Next we create a user define function for z coordinate.
  • Then by using np.linspace() function we define data for x and y coordinates.
  • By using plt.figure() method we create a function and plt.axes() method to define axes.
  • ax.plot_surface() method is used to plot 3D scatter with surface.
  • To dispaly the figure, use show() method.
matplotlib 3d scatter with surface
ax.plot_surface()

Read: Matplotlib title font size

Matplotlib 3D scatter transparency

Here we will learn how to adjust the opacity or transparency of the 3D scatter plot. By using the alpha attribute we can change the transparency of the plot in matplotlib.

By default, alpha is 1. It ranges between 0 to 1. We can decrease the transparency by decreasing the value of alpha.

The syntax to change the transparency is given below:

matplotlib.axis.Axis.scatter3D(x, y, z, alpha=1)

Here x, y, z are data coordinates, and alpha is used to set transparency.

Let’s see an example where we change the transparency of the plot:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

x = np.arange(0, 20, 0.2)
y = np.sin(x)
z = np.cos(x)
 
# Create Figure

fig = plt.figure(figsize = (10, 7))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x, y, z)
                      # OR

ax.scatter3D(x, y, z, alpha=0)

                      # OR

ax.scatter3D(x, y, z, alpha=0.5)

                      # OR

ax.scatter3D(x, y, z, alpha=1)

 
# Show plot

plt.show()
  • In the above example, we define data using arange(), sin(), cos() method.
  • By using the figure() function we create figure, axes() method is used to define projection to 3d.
  • ax.scatter3D() method is used to plot 3D scatter graph, we pass alpha argument to change opacity.
matplotlib 3d scatter transparency
” Scatter3D plot without alpha argument “
matplotlib 3d scatter having transparency
” Scatter3D plot with alpha=0 “
matplotlib 3d scatter consist transparency
” Scatter3D plot with alpha=0.5 “
matplotlib 3d scatter own transparency
” Scatter3D plot with alpha=1 “

Read: Matplotlib save as pdf + 13 examples

Matplotlib 3D sactter depthshade

In general, when we plot a 3D scatter graph, the data points’ transparency is adjusted by distance. This means that transparency increases and decreases by a distance of points.

So in general, we see some data points having dark colors and some are transparent.

By using the depthshade attribute we can turn off the transparency in matplotlib. To turn it off set its value to False.

The syntax is given below:

matplotlib.axis.Axis.scatter3D(x, y, z, depthshade=False)

Let’s see an example:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

z = [3, 6, 9, 12, 15]
x = [2, 4, 6, 8, 10]
y = [5, 10, 15, 20, 25]
 
# Create Figure

fig = plt.figure(figsize = (10, 7))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x, y, z, s=100, color='green',   depthshade=False)

# Add axis

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

# Show plot

plt.show()

Here we use the ax.scatter3D() method to plot 3D scatter graph and we pass the depthshade attribute to turn off its transparency.

matplotlib 3d scatter depthshade
” 3D scatter Plot with depthshade attribute “

Here you see transparency in the 3D scatter plot.

matplotlib 3d scatter having depthshade
” 3D Scatter Plot with depthshade attribute “

Here you see there is no transparency in data points.

Read: Put legend outside plot matplotlib

Matplotlib 3D scatter axis limit

Here we are going to learn how to change the axis limit of the 3D scatter plot. By default, the range of values on the axes is set automatically based on the input values.

To modify the minimum and maximum limit on each axis we use set_xlim(), set_ylim(), and set_zlim() methods.

The syntax to modify axis limits is given below:

# For x-axis limit
matplotlib.axis.Axis.set_xlim(min, max)

# For y-axis limit
matplotlib.axis.Axis.set_ylim(min, max)

# For z-axis limit
matplotlib.axis.Axis.set_zlim(min, max)

Let’s see an example where we adjust axis limits:

Code: With default axis

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Define Data

x1 = np.random.randint(450,size=(80))
y1 = np.random.randint(260, size=(80))
z1 = np.random.randint(490, size=(80))

# Create Figure

fig = plt.figure(figsize = (8,6))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x1, y1, z1, s=50, color='red')

# Show plot

plt.show()

Here we draw a 3D scatter plot by using the ax.scatter3D() method. And we use np.random.randint() method to define data.

matplotlib 3d scatter axis limit
” 3D Scatter Plot “

Code: With the modified axis

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Define Data

x1 = np.random.randint(450,size=(80))
y1 = np.random.randint(260, size=(80))
z1 = np.random.randint(490, size=(80))

# Create Figure

fig = plt.figure(figsize = (8,6))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x1, y1, z1, s=50, color='red')

# Modify axis

ax.set_xlim(50,150)
ax.set_ylim(30,160)
ax.set_zlim(0,350)

# Show plot

plt.show()

Here we use set_xlim(), set_ylim(), set_zlim() methods to modify the limits for three axes based on min and max values passed.

matplotlib 3d scatter having axis limit
” 3D Scatter Plot with modified axes “

Read: Draw vertical line matplotlib

Matplotlib 3D scatter axis ticks

Here we are going to learn how to change axis ticks of a 3D scatter plot. We can modify the ticks for each axis. The methods used to modify ticks is set_xticks(), set_yticks(), set_zticks().

The syntax to modify axis limits is given below:

# For x-axis limit
matplotlib.axis.Axis.set_xticks()

# For y-axis limit
matplotlib.axis.Axis.set_yticks()

# For z-axis limit
matplotlib.axis.Axis.set_zticks()

Let’s see an example where we adjust axis ticks:

Code: With default ticks

# Import libraries


from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data


x = np.arange(0, 20, 0.2)
y = np.sin(x)
z = np.cos(x)
 
# Create Figure


fig = plt.figure(figsize = (8,6))
ax = plt.axes(projection ="3d")
 
# Create Plot


ax.scatter3D(x, y, z)
 
# Show plot


plt.show()

Here we use ax.scatter3D() method to plot 3D scatter graph. To define data use arange(), sin(), and cos() methods.

matplotlib 3d scatter axis ticks
” 3D Scatter Plot “

Here x-axis ticks are [0.0, 2.5, 5.0, 7.5, 10.0, 12.5, 15.5, 17.5, 20.0]

Code: With modify ticks

# Import libraries


from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data


x = np.arange(0, 20, 0.2)
y = np.sin(x)
z = np.cos(x)
 
# Create Figure


fig = plt.figure(figsize = (8,6))
ax = plt.axes(projection ="3d")
 
# Create Plot


ax.scatter3D(x, y, z)

# Set tick labels


ax.set_xticks([1.5, 3.5, 5.5, 7.5, 12.5, 14.5, 16.5, 18.5])
 
# Show plot


plt.show()

Here we use the ax.set_xticks() method and pass a list of x ticks to modify x-axis ticks.

matplotlib 3d scatter having axis ticks
” 3D axis with modifying x ticks “

Now x ticks are [1.5, 3.5, 5.5, 7.5, 12.5, 14.5, 16.5, 18.5].

We can also update Y ticks and Z ticks using set_yticks() and z_ticks() methods respectively.

Read: Stacked Bar Chart Matplotlib

Matplotlib 3D scatter size

Here we will be going to learn how we can change the size of the 3D scatter plot. We can easily make our plots bigger or smaller than the default size.

The following ways are used to change the size of the plot:

  • Using plt.figure() method
  • Using set_size_inches() method

By using plt.figure() method

We pass the figsize parameter to the plt.figure() method to change the size of the plot. We must have to specify the width and height of the plot in inches.

The syntax for this is given below:

matplotlib.pyplot.figure(figsize(w,h))

Here w and h specify width and height

Let’s see an example:

# Import libraries


from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data


x = np.arange(0, 20, 0.2)
y =  np.sin(x)
z = np.exp(8)
 
# Change figure size


fig = plt.figure(figsize = (10, 7))
ax = plt.axes(projection ="3d")
 
# Create Plot


ax.scatter3D(x, y, z, marker='<', s=20)

# Show plot


plt.show()

Here we use the figsize argument of plt.figure() method to change the figure size. We set w = 10 and h= 7.

matplotlib 3d scatter size
plt.figure(figsize())

By using set_size_inches() method

We pass the width and height of the plot in inches to the set_size_inches() method to modify the size of the plot.

The syntax for this is given below:

matplotlib.figure.Figure.set_size_inches(w,h)

Here w and h specify width and height.

Let’s see an example:

# Import libraries


from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data


z = [3, 6, 9, 12, 15, 23, 14, 16, 21]
x = [2, 4, 6, 8, 10, 13, 18, 16, 15]
y = [5, 10, 15, 20, 25, 32, 29, 45, 20]
 
# Change figure size


fig = plt.figure()
fig.set_size_inches(10, 10)


ax = plt.axes(projection ="3d")
 
# Create Plot


ax.scatter3D(x, y, z)

# Add axis


ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

# Show plot


plt.show()

Here we use the set_size_inches() method of the figure to modify the size of the plot.

matplotlib 3d scatter sizes
fig.set_size_inches()

Here we set the width and height of the plot to 10 inches.

Read: Matplotlib two y axes

Matplotlib 3D scatter grid

When we plot a 3D scatter plot by default all the plots have gridlines. We can remove the grid lines if we want. To remove the grid lines, call the grid() method of the axes object.

Pass the value ‘False’ to remove gridlines and to get it back again pass the value ‘True’.

The syntax for this is given below:

matplotlib.axis.Axis.grid()

Let’s see an example of a 3D scatter plot without a grid:

# Import libraries


from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Define Function


def function_z(x,y):
    return np.cos(x ** 2 + y ** 2)

# Define Data


x_val = np.linspace(-3, 3, 30)
y_val = np.linspace(-3, 3, 30)

X, Y = np.meshgrid(x_val, y_val)

# Call function


z = function_z(X, Y)

# Create figure


fig = plt.figure(figsize =(10,6))
ax = plt.axes(projection='3d')

# Create surface plot


ax.plot_surface(X, Y, z);

# Grid


ax.grid(False)

# Display


plt.show()
  • In the above example, we define z-axis using user define function and x-axis, y-axis are define using linspace() method of numpy.
  • Then we use ax.plot_surface() method to draw 3D scatter plot with surface.
  • We use ax.grid() method and pass keyword False to turn off the grid lines.
matplotlib 3d scatter grid
ax.grid(False)

Matplotlib 3D scatter subplot

Here we will discuss how we can plot a 3D scatter graph in one of the specific subplots out of multiple plots.

We use the scatter3D() method to create 3D scatter plot.

Let’s understand the concept with the help of an example:

# Importing Libraries

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

# Create 1st subplot

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(1, 2, 1, projection='3d')

# Define Data

x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]
z1= [2, 6, 7, 9, 10]

# Plot graph

ax.scatter3D(x1, y1, z1, color='m')

# Create 2nd subplot

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

# Define Data

x2 = np.arange(0, 20, 0.2)
y2 = np.sin(x)
z2 = np.cos(x)

# Plot graph

ax.scatter3D(x2, y2, z2, color='r')

# Display graph

fig.tight_layout()
plt.show()
  • In the above example, by using add_subplot() method we create 1st subplot and then we define data used to for plotting.
  • ax.scatter3D() method is used to create 3D scatter plot.
  • After this, again we use add_subplot() method to create 2nmd subplot and then we define data which is used for plotting.
  • Again, we use ax.scatter3D() method to plot another 3D scatter graph.
matplotlib 3d scatter subplot
” 3D Scatter Subplots “

Matplotlib 3D scatter save

Here we are going to learn how we can save 3D scatter plots in our system memory. We save the 3D scatter plot in “png”.

To save it we use savefig() method of matplotlib and pass the path where you want to save it.

Let’s see an example:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Define Data

x1 = np.random.randint(450,size=(80))
y1 = np.random.randint(260, size=(80))
z1 = np.random.randint(490, size=(80))

# Create Figure

fig = plt.figure(figsize = (8,6))
ax = plt.axes(projection ="3d")
 
# Create Plot

ax.scatter3D(x1, y1, z1, s=50, color='red')

# save plot

plt.savefig('3D Scatter Plot.png')

# Show plot

plt.show()
  • In the above example, we use random.randit() method to define data and scatter3D() method to draw 3D scatter plot.
  • Then we use plt.savefig() method to save plot in our system and we pass path as an argument to the function.
matplotlib 3d scatter save
plt.savefig()

Matplotlib 3D scatter background color

set_facecolor() method in the axes module is used to change or set the background color of the plot.

It is used to set the face color of the figure or we can say the axes color of the plot. Pass the argument as a color name that you want to set.

figure(facecolor=’color’) method is used to change the outer background color of the plot.

The syntax to change the background color of the plot is below:

# Inner color
matplotlib.pyplot.axes.set_facecolor(color=None)

# Outer color 
plt.figure(facecolor=None) 

Let’s understand the concept with the help of an example:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
 
# Define Data

x = np.arange(0, 20, 0.2)
y = np.sin(x)
z = np.cos(x)
 
# Create Figure 

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

# Set Outer color


plt.figure(facecolor='red')

ax = plt.axes(projection ="3d")

# Set Inner color


ax.set_facecolor('yellow')
 
# Create Plot


ax.scatter3D(x, y, z, marker= '>', s=50)
 
# Show Plot

plt.show()
  • In the above example, we have changed both the inner and outer colors of the background of the plot.
  • The “facecolor” attribute is used in the figure() method to change the outer area color.
  • The “set_facecolor()” method of the axes() object to change the inner area color of the plot.
matplotlib 3d scatter background color
” 3D Scatter Background Color “

Here we set the inner color to “yellow” and the outer color to “red”.

Matplotlib 3D scatter numpy array

Here we are going to learn how to create a 3D scatter plot using numpy array.

To define the three-dimensional data axis of the 3D scatter plot we use numpy methods.

Let’s see an example:

# Import libraries


from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Create Figure 


fig = plt.figure(figsize = (8,8))
ax = plt.axes(projection ="3d")


 
# Define Data using numpy


data = np.random.randint(2, 10, size=(3, 3, 3))
x , y , z = data.nonzero()

# Create Plot


ax.scatter3D(x, y, z, s=50)
 
# Show plot


plt.show()
  • In the above example, we create a 3D array using numpy and extra three-dimensional data points.
  • Firstly, we import mplot3d, numpy, and pyplot libraries and then we create a new figure using the figure() method.
  • By using the numpy random.randint() method we create data.
  • Then by using the nonzero() method we extra x, y, and z data points to plot 3D scatter plot.
  • Next, we use the ax.scatter3D() method to plot 3D scatter points on the created axis.
  • To display the figure, we use the show() method.
matplotlib 3d scatter numpy array
” 3D Scatter Plot Using Numpy Array “

Matplotlib 3D scatter marker color

Here we are going to learn how to change marker color in 3D scatter graph.

In 3D scatter plot the data points are represented by using points and these points are known as markers.

So, to change the color of the marker we simply pass color as an argument to the scatter3D() method, and to change the edge color of the marker we use edgecolor as an argument in the scatter3D() method.

The syntax to change color and edge color of the marker:

matplotlib.axis.Axis.scatter3D(x, y, z, color=None, edgecolr=None)

The parameters used above are:

  • x: specify x-axis coordinates.
  • y: specify y-axis coordinates.
  • z: specify z-axis coordinates.
  • color: specify the color of the marker.
  • edgecolor: specify the edge color of the marker.

Example:

# Import libraries

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Create Figure 

fig = plt.figure(figsize = (8,8))
ax = plt.axes(projection ="3d")

# Define Data using numpy


data = np.random.random(size=(5, 4, 3))
x , y , z = data.nonzero()
 
# Create Plot and set color and edge color

ax.scatter3D(x, y, z, s=150, color='yellow', edgecolor='black')
 
# Show plot

plt.show()
  • In the above example, we use the scatter3D() method and pass a color argument to set marker color. Here we set the color of the marker to “yellow”.
  • We also pass the edgecolor argument to the scatter3D() method to change the color of the edges of the markers. Here we set the edgecolor of the marker to “black”.
matplotlib 3d scatter marker color
” 3D Scatter Plot Color and Edgecolor “

Matplotlib 3D scatter zlim

set_zlim() method is used to set limits of the z-axis.

The syntax of the zlim() method is given below:

matplotlib.axis.Axis.set_zlim(min, max)

Let’s see examples of the zlim() method:

Example 1

# Import Library

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Plotting 3D axis figures

fig = plt.figure(figsize = (8, 6))
ax = plt.axes(projection = '3d')
  
# Define Data

z = np.linspace(0,15,150)
x = np.sin(z)
y = np.cos(z)

# Plot 3D scatter 

ax.scatter3D(x, y, z)

# zlim() method

ax.set_zlim(-1.5, 4)

# Display

plt.show()

Here we use the set_zlim() method to set limits of the z-axis. We set the minimum limit to -1.5 and the maximum limit to 4.

matplotlib 3d scatter zlim
set_zlim()

Example 2

# Importing Libraries

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

# Create figure

fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(1, 2, 1, projection='3d')

# Define Data

x= [0.2, 0.4, 0.6, 0.8, 1]
y= [0.3, 0.6, 0.8, 0.9, 1.5]
z= [2, 6, 7, 9, 10]

# Plot graph

ax.scatter3D(x, y, z, color='m', depthshade=False)

# zlim() method

ax.set_zlim(3, 6)

# Display

plt.show()

In the above example, we use the set_zlim() method to set the minimum and maximum limit of the z-axis. Here we set a range from 3 to 6.

matplotlib 3d scatter having zlim
set_zlim()

Matplotlib 3D scatter zlabel

set_zlabel() method is used to add a label to the z-axis of the plot.

The syntax of zlabel() method:

matplotlib.axis.Axis.set_zlabel()

Let’s see examples of the zlabel() method:

Example:

# Import Library


from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Plotting 3D axis figures


fig = plt.figure(figsize = (4,6))
ax = plt.axes(projection = '3d')
  
# Define Data


x = np.random.randint(150, size=(50))
y = np.random.randint(260, size=(50))
z = np.random.randint(450, size=(50))

# Plot 


ax.scatter3D(x, y, z, 'green')

# zlabel()


ax.set_zlabel('Quality')

# Display


plt.show()

In the above example, we use the set_zlabel() method to add a label to the z-axis.

matplotlib 3d scatter zlabel
ax.set_zlabel()

Matplotlib 3d scatter xlim

set_xlim() method is used to set limits of the x-axis.

The syntax of the xlim() method is given below:

matplotlib.axis.Axis.set_xlim(min, max)

Let’s see examples of the xlim() method:

# Import Library

from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Plotting 3D axis figures


fig = plt.figure(figsize = (4,6))
ax = plt.axes(projection = '3d')
  
# Define Data

x = np.random.randint(150, size=(50))
y = np.random.randint(260, size=(50))
z = np.random.randint(450, size=(50))

# Plot 

ax.scatter3D(x, y, z, s=60)

# xlim()

ax.set_xlim(35,62)

# Display

plt.show()

Here we use the set_xlim() method to set the limit. We set its range between 35 to 62.

matplotlib 3d scatter xlim
set_xlim()

Matplotlib 3D scatter zoom

In matplotlib zoom() method is used to zoom in or out on axes.

The syntax of the zoom() method is given below:

matplotlib.axis.Axis.zoom(self, direction)

Here direction>0 is used for zoom in and direction<=0 is used for zoom out.

Let’s see an example:

Code:

# Importing Libraries


import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d

# Create 1st subplot


fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(1, 2, 1, projection='3d')

# Define Data


x1= [0.2, 0.4, 0.6, 0.8, 1]
y1= [0.3, 0.6, 0.8, 0.9, 1.5]
z1= [2, 6, 7, 9, 10]

# Plot graph


ax.scatter3D(x1, y1, z1, color='m', depthshade=False)

# For zoom


ax.xaxis.zoom(-2.5)

# Display


plt.show()
  • In the above example, we import numpy, pyplot, and mplot3d libraries.
  • Then we create a figure by using the figure() method and define data using random.randint() method of numpy.
  • ax.scatter3D() method is used to draw 3D scatter graph.
  • Then we use the zoom() method for zoom in and zoom out of axes.

Output:

matplotlib 3d scatter zoom

You will get a warning like that because the zoom() method was deprecated from matplotlib 3.3

Matplotlib 3D scatter origin

In matplotlib, we can get the origin of 3D to scatter origin. To get an origin we use the zeros() method of the NumPy library.

Let’s see an example:

# Import libraries


from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

# Create Figure 


fig = plt.figure(figsize = (8,8))
ax = plt.axes(projection ="3d")

# Define Data 


x , y , z = np.zeros((3,3))
 
# Create Plot and set color and edge color


ax.scatter3D(x, y, z, s=150, color='yellow', edgecolor='black')
 
# Show plot


plt.show()
  • In the above example, we import libraries mplot3d, numpy, and pyplot of matplotlib.
  • Then we create a figure by using the figure() method.
  • After this, to get the origin of the 3D scatter plot we use the np.zeros() method.
  • ax.scatter3D() method is used to draw scatter plots in the 3D plane.
matplotlib 3d scatter origin
“3D Scatter Origin”

Matplotlib 3D scatter log scale

Here we are going to learn how we can set axis scales value to log scale.

Let’s see an example of 3D scatter with a log scale:

# Import libraries


from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

# Define Function


def function_z(x,y):
    return 100 - (x**2 + y**2)

# Define Data


x_val = np.linspace(-3, 3, 30)
y_val = np.linspace(-3, 3, 30)

X, Y = np.meshgrid(x_val, y_val)

# Call function


z = function_z(X, Y)

# Create figure


fig = plt.figure(figsize =(10,6))
ax = plt.axes(projection='3d')

# Create surface plot


ax.plot_surface(X, Y, z, color='yellow');

# Log Scale


def log_tick_formatter(val, pos=None):
    return f"$10^{{{int(val)}}}$"
ax.zaxis.set_major_formatter(mticker.FuncFormatter(log_tick_formatter))
ax.zaxis.set_major_locator(mticker.MaxNLocator(integer=True))

# Set Title


ax.set(title="Logarithmic z-aix")


# Display


plt.show()
  • In the above example, we import mplot3d, numpy, pyplot, and ticker libraries of matplotlib.
  • Then we create user-define function to define the z coordinate.
  • After this, we define x and y coordinates and create figure using the figure() method.
  • ax.plot_surface() method is used to create surface plot in 3D.
  • Then we create user-define function to create a major locator and we define ticks in log form.
matplotlib 3d scatter log scale
“3D Scatter Log Scale”

Here we set the z-axis in form of a log.

Matplotlib 3D scatter Dataframe

Here we are going to learn how can we create a 3D scatter plot by using pandas data frame.

Let’s see an example:

# Import Library


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from mpl_toolkits import mplot3d

# Create figure


fig = plt.figure(figsize = (4,6))
ax = plt.axes(projection = '3d')

# Define dataframe


df=pd.DataFrame(np.random.rand(30,20))
x = df.iloc[:,0]
y = df.iloc[:,5]
z = df.iloc[:,10]

# Plot 3d Scatter Graph


ax.scatter3D(x,y,z)

# Display


plt.show()
  • In the above example, we import pyplot, numpy, pandas, and mplot3d library in matplotlib.
  • After this, we create figures by using the figure() method and define projection in 3D.
  • Then we create pandas DataFrame and we use np.random.rand() method.
  • We define x, y, and z data coordinates by using iloc() method of dataframe in pandas.
  • ax.scatter3D() method is used to create 3D scatter graph.
matplotlib 3d scatter dataframe
“3D Scatter DataFrame”

Matplotlib 3D scatter animation

Here we are going to learn how we can create a 3D scatter plot with animations.

Let’s see an example of an animated 3D Scatter Plot:

# Interactive Mode


%matplotlib notebook

# Import Library


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.animation import FuncAnimation, PillowWriter 

# Define Data


data = np.random.random(size=(1000,3))
df = pd.DataFrame(data, columns=["x","y","z"])

# Create Figure


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

# Plot Graph


scatter_plot = ax.scatter3D([],[],[], color='m')

# Define Update function


def update(i):
    scatter_plot._offsets3d = (df.x.values[:i], df.y.values[:i], df.z.values[:i])

# Set annimation


ani = matplotlib.animation.FuncAnimation(fig, update, frames=len(df), interval=50)


# Show


plt.tight_layout()
plt.show()

# Save


ani.save('3D Scatter Animation.gif', writer='pillow', fps=30)
  • In this above example, we firstly enable Interactive Mode.
  • Then we import pandas, numpy, pyplot, mplot3d, and animation libraries of matplotlib.
  • Next, we define data using random.random() method of numpy.
  • After this, we create DataFrame in pandas and define x, y, and z coordinates.
  • plt.figure() method is used to create a figure and add_subplot() method create subplot and we set the projection to 3D.
  • ax.scatter3D() method is used to draw 3D scatter plot.
  • After this, we create an update function.
  • By using animation.FuncAnimation() method we add animation in the 3D Scatter Plot.
  • Then, at last, we use the save() method to save a plot as a gif.
3D Scatter Animation
” 3D Scatter Animation “

In this Python tutorial, we have discussed the “Matplotlib 3D Scatter” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Matplotlib 3D scatter plot
  • Matplotlib 3D scatter plot example
  • Matplotlib 3D scatter color
  • Matplotlib 3D scatter with colorbar
  • Matplotlib 3D scatter marker size
  • Matplotlib 3D scatter label
  • Matplotlib 3D scatter legend
  • Matplotlib 3D scatter plot color by value
  • Matplotlib 3D scatter rotate
  • Matplotlib 3D scatter change view angle
  • Matplotlib 3D scatter title
  • Matplotlib 3D scatter text
  • Matplotlib 3D scatter with line
  • Matplotlib 3D scatter with surface
  • Matplotlib 3D sactter transparency
  • Matplotlib 3D sactter depthshade
  • Matplotlib 3D scatter axis limits
  • Matplotlib 3D scatter axis ticks
  • Matplotlib 3D scatter size
  • Matplotlib 3D scatter grid
  • Matplotlib 3D scatter subplot
  • Matplotlib 3D scatter save
  • Matplotlib 3D scatter background color
  • Matplotlib 3D scatter numpy array
  • Matplotlib 3D scatter marker color
  • Matplotlib 3D scatter zlim
  • Matplotlib 3D scatter z label
  • Matplotlib 3D scatter xlim
  • Matplotlib 3D scatter zoom
  • Matplotlib 3D scatter origin
  • Matplotlib 3D scatter log scale
  • Matplotlib 3D scatter dataframe
  • Matplotlib 3D scatter animation