Matplotlib scatter() Function


Matplotlib 参考文档Matplotlib Reference Documentation

scatter()Used to draw scatter plots, each data point can independently set size, color, and transparency.

Unlike plot(), scatter() allows each point to have different appearance attributes, making it suitable for displaying the distribution relationship of three-dimensional or four-dimensional data.

Function Definition

pyplot Interface

matplotlib.pyplot.scatter(x, y, s=None, c=None, marker='o', cmap=None,
    norm=None, vmin=None, vmax=None, alpha=None, linewidths=None,
    edgecolors=None, **kwargs)

Axes Interface

Axes.scatter(x, y, s=None, c=None, marker='o', cmap=None, norm=None,
    vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None,
    **kwargs)

Parameter Description

ParameterTypeDescription
x, yarray-likeThe x and y coordinates of the data points (required)
sfloat or array-likeThe size of the points, can be a scalar (all points the same) or an array (each point a different size)
ccolor or array-likeThe color of the points, can be a fixed color or a numeric array (used with cmap to map colors)
markerstrMarker shape: 'o' (circle), 's' (square), '^' (upward triangle), 'v' (downward triangle), 'D' (diamond), '*' (star), '+' (plus), 'x' (cross), etc., default is 'o'
cmapstr or ColormapColor mapping, used when c is a numeric array, such as 'viridis', 'plasma'
normNormalizeThe normalization method for mapping data to colors
vmin, vmaxfloatThe data range for color mapping; points outside the range will be clipped
alphafloat or array-likeTransparency, between 0-1
linewidthsfloat or array-likePoint edge line width
edgecolorscolor or array-likePoint edge color, 'face' uses the fill color, 'none' means no edge
labelstrLegend label

The core advantage of scatter() is thats、c、alphait can be arrays of the same length as x/y, which allows a single scatter plot to display 3-4 dimensions of data information at the same time.


Usage Examples

Example 1: Basic Scatter Plot

Example

import matplotlib.pyplot as plt
import numpy as np

# Generate random data
np.random.seed(42)
x = np.random.rand(50)
y = np.random.rand(50)

fig, ax = plt.subplots(layout='constrained')

ax.scatter(x, y, color='steelblue', edgecolors='white',
           linewidth=0.5, s=80)
ax.set_title('Basic Scatter Plot')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.grid(True, alpha=0.3)
plt.show()

Example 2: Varying Size and Color (Displaying Multidimensional Data)

Example

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)
n = 100

# Four dimensions of data
x = np.random.rand(n) * 10           # Dimension 1: x coordinate
y = np.random.rand(n) * 10           # Dimension 2: y coordinate
colors = np.random.rand(n) * 100     # Dimension 3: color (numeric)
sizes = np.random.rand(n) * 300      # Dimension 4: size
alpha_values = np.random.rand(n) * 0.7 + 0.3  # Dimension 5: transparency

fig, ax = plt.subplots(figsize=(8, 6), layout='constrained')

scatter = ax.scatter(x, y,
                     c=colors,           # Color changes with data
                     s=sizes,            # Size changes with data
                     alpha=0.6,          # Fixed transparency
                     cmap='viridis',     # Color mapping
                     edgecolors='white',
                     linewidth=0.5)

# Add color bar
cbar = fig.colorbar(scatter, ax=ax)
cbar.set_label('Color Value')

ax.set_title('Multi-dimensional Scatter Plot')
ax.set_xlabel('X Coordinate')
ax.set_ylabel('Y Coordinate')
ax.grid(True, alpha=0.2)
plt.show()

Example 3: Comparing Multiple Scatter Groups

Example

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(42)

# Generate three groups of data with different distributions
group1_x = np.random.normal(2, 0.5, 100)
group1_y = np.random.normal(2, 0.5, 100)

group2_x = np.random.normal(6, 0.5, 100)
group2_y = np.random.normal(6, 0.5, 100)

group3_x = np.random.normal(4, 1.0, 100)
group3_y = np.random.normal(4, 1.0, 100)

fig, ax = plt.subplots(figsize=(8, 6), layout='constrained')

# Each group uses a different color and marker
ax.scatter(group1_x, group1_y, c='#e74c3c', marker='o',
           s=60, label='Group A (tight cluster)')
ax.scatter(group2_x, group2_y, c='#2E7DCC', marker='s',
           s=60, label='Group B (tight cluster)')
ax.scatter(group3_x, group3_y, c='#3498db', marker='^',
           s=60, label='Group C (spread cluster)')

ax.set_title('Multi-group Scatter Comparison')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.legend()
ax.grid(True, alpha=0.2)
plt.show()

Example 4: Scatter Plot with Color Bar (Bubble Chart)

Example

import matplotlib.pyplot as plt
import numpy as np

# Simulated data: population, GDP, and region of different cities
np.random.seed(42)
n = 30
population = np.random.randint(50, 500, n)    # Population (determines bubble size)
gdp = np.random.randint(100, 1000, n)         # GDP (determines color intensity)
region = np.random.choice(['North', 'South', 'East', 'West'], n)
x = np.random.rand(n) * 100
y = np.random.rand(n) * 100

fig, ax = plt.subplots(figsize=(9, 6), layout='constrained')

scatter = ax.scatter(x, y,
                     s=population,            # Bubble size = population
                     c=gdp,                   # Bubble color = GDP
                     cmap='YlOrRd',           # Yellow-orange-red color mapping
                     alpha=0.7,
                     edgecolors='gray',
                     linewidth=0.5)

ax.set_title('Bubble Chart: City Population vs GDP')
ax.set_xlabel('X Coordinate')
ax.set_ylabel('Y Coordinate')

# Add a color bar, labeled as GDP
cbar = fig.colorbar(scatter, ax=ax, label='GDP')
ax.grid(True, alpha=0.2)
plt.show()

Frequently Asked Questions

What's the difference between scatter() and plot()?

plot()Suitable for line charts, all points share the same color and marker style, with high rendering efficiency.

scatter()Suitable for scatter plots, each point can independently set size and color, but each point is an independent Artist, making it slower with large amounts of data.

When there are many data points (tens of thousands or more), prioritize plot() with a specified marker to improve performance.

What is the unit of the s parameter?

sIt represents the area of the point (unit: square points, points^2), not the diameter.

For examples=100ands=400, the latter has 4 times the area of the former, and the diameter is about 2 times that of the former.


Matplotlib 参考文档Matplotlib Reference Documentation

Other Extensions