Skip to content

Matplotlib - Scatter Plot

Scatter plots are used to visualize the relationship between two numerical variables. Each data point in the dataset is represented as a marker (e.g., a dot, circle, cross) on a 2D plane, with its position determined by its values on the horizontal (x) and vertical (y) axes.

Scatter plots are excellent for identifying patterns like:

  • Correlation: Positive (y tends to increase as x increases), negative (y tends to decrease as x increases), or no correlation.
  • Clusters: Groups of data points forming distinct clumps.
  • Outliers: Points that lie far away from the main body of data.
  • Trends: Linear or non-linear relationships between variables.

The ax.scatter() method is used to create scatter plots.

ax.scatter(x, y, s=None, c=None, marker=None, cmap=None, alpha=None, **kwargs)
  • x, y: Array-like. The horizontal and vertical coordinates of the data points.
  • s: Scalar or array-like (default: rcParams['lines.markersize']**2). Size(s) of the markers in points^2. Can be used to encode a third variable.
  • c: Color, sequence, or sequence of colors. Marker color(s). Can be: - A single color format string (e.g., 'red', '#FF0000'). - A sequence of colors of the same size as x and y. - A sequence of numerical values mapped to colors via cmap and norm (encoding a third variable).
  • marker: String (default: 'o'). The marker style (e.g., 'o', '.', ',', 'x', '+', 's' for square, 'd' for diamond).
  • cmap: String or Colormap instance (default: rcParams['image.cmap']). Colormap used only if c is an array of floats.
  • alpha: Float (0.0 transparent through 1.0 opaque). Blending value for markers, useful for overlapping points.
  • linewidths: Scalar or array-like. Width of the marker edge.
  • edgecolors: Color or sequence of colors. Color of the marker edge.
  • label: String. Label for the points, used by ax.legend().

Example: Scatter plot showing relationship between two variables, potentially encoding a third via color or size.

import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
np.random.seed(42)
num_points = 100
x_coords = np.random.rand(num_points) * 10 # X values between 0 and 10
y_coords = 2.5 * x_coords + np.random.randn(num_points) * 3 # Y values with linear trend + noise
# Generate a third variable for color/size encoding (optional)
point_sizes = np.random.rand(num_points) * 150 # Sizes for markers
point_colors = np.random.rand(num_points) # Values to map to color
# --- Create the Scatter Plot ---
fig, ax = plt.subplots(figsize=(8, 6))
scatter_plot = ax.scatter(x_coords, y_coords,
s=point_sizes, # Set marker size based on 'point_sizes'
c=point_colors, # Set marker color based on 'point_colors'
marker='o', # Use circle markers
cmap='viridis', # Colormap to use for 'point_colors'
alpha=0.7, # Make markers slightly transparent
edgecolors='black', # Add black edges to markers
linewidths=0.5,
label='Data Points' # Label for legend
)
# --- Customize and Label ---
ax.set_title('Scatter Plot Example (Size & Color Encoded)')
ax.set_xlabel('X Variable')
ax.set_ylabel('Y Variable')
ax.grid(True, linestyle='--', alpha=0.6)
# Add a colorbar to show the mapping for 'point_colors'
cbar = fig.colorbar(scatter_plot, label='Color Variable Value')
# Add a legend (if using 'label' and wanting to explain marker type)
# Create proxy artists for size legend (more complex)
handles, labels = scatter_plot.legend_elements(prop="sizes", alpha=0.6, num=4)
size_legend = ax.legend(handles, labels, loc="upper left", title="Sizes")
plt.show()

This example creates a scatter plot where the position of each point is determined by x_coords and y_coords. Additionally, the size of each marker is determined by the point_sizes array, and the color is determined by the point_colors array, mapped using the ‘viridis’ colormap. This allows visualizing up to four dimensions of data on a single 2D plot (x, y, size, color). A colorbar is added to explain the color mapping, and a basic legend explains the marker sizes.