How can I create a 3D plot with a color gradient for the points? See the example below, which works for a 2D scatter plot.
Edit [thanks to Chris]: What I'm expecting to see from the 3D plot is a color gradient of the points ranging from red to green as in the 2D scatter plot. What I see in the 3D scatter plot are only red points.
Solution: for some reasons [related to the gradient example I copied elsewhere] I set xrange to len-1, which messes everything in the 3D plot.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Create Map
cm = plt.get_cmap["RdYlGn"]
x = np.random.rand[30]
y = np.random.rand[30]
z = np.random.rand[30]
#col = [cm[float[i]/[29]] for i in xrange[29]] # BAD!!!
col = [cm[float[i]/[30]] for i in xrange[30]]
# 2D Plot
fig = plt.figure[]
ax = fig.add_subplot[111]
ax.scatter[x, y, s=10, c=col, marker='o']
# 3D Plot
fig = plt.figure[]
ax3D = fig.add_subplot[111, projection='3d']
ax3D.scatter[x, y, z, s=10, c=col, marker='o']
plt.show[]
asked Jan 17, 2012 at 9:08
andrea.geandrea.ge
1,9171 gold badge18 silver badges27 bronze badges
3
Here is an example for 3d scatter with gradient colors:
import matplotlib.cm as cmx
from mpl_toolkits.mplot3d import Axes3D
def scatter3d[x,y,z, cs, colorsMap='jet']:
cm = plt.get_cmap[colorsMap]
cNorm = matplotlib.colors.Normalize[vmin=min[cs], vmax=max[cs]]
scalarMap = cmx.ScalarMappable[norm=cNorm, cmap=cm]
fig = plt.figure[]
ax = Axes3D[fig]
ax.scatter[x, y, z, c=scalarMap.to_rgba[cs]]
scalarMap.set_array[cs]
fig.colorbar[scalarMap]
plt.show[]
Of course, you can choose the scale to range between different values, like 0 and 1.
answered Nov 27, 2014 at 21:59
Noam PeledNoam Peled
4,2763 gold badges42 silver badges48 bronze badges
3
Following works: I can't figure out why yours doesn't. You should be able to set color as a sequence of RGBA floats, or just sequence of floats.
# Create Map
cm = plt.get_cmap["RdYlGn"]
x = np.random.rand[30]
y = np.random.rand[30]
z = np.random.rand[30]
col = np.arange[30]
# 2D Plot
fig = plt.figure[]
ax = fig.add_subplot[111]
ax.scatter[x, y, s=10, c=col, marker='o']
# 3D Plot
fig = plt.figure[]
ax3D = fig.add_subplot[111, projection='3d']
p3d = ax3D.scatter[x, y, z, s=30, c=col, marker='o']
plt.show[]
However, in help of scatter, I see the following, it may be related.
A :class:`matplotlib.colors.Colormap` instance or registered
name. If *None*, defaults to rc ``image.cmap``. *cmap* is
only used if *c* is an array of floats.
answered Jan 17, 2012 at 9:58
CenkolojiCenkoloji
931 silver badge5 bronze badges
2
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
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.
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.
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.
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.
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:
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=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.
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 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 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.
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 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 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 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