Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 57 ยท Core Chart Types

Scatter Plots

Draw scatter plots in Matplotlib: scatter vs plot, size and color encodings, alpha for overplotting, bubble charts, colorbars and a polyfit trend line.

A scatter plot puts one dot per observation, with one variable on each axis. It is the first chart to reach for when you ask "are these two things related?": height and weight, ad spend and revenue, study hours and exam score. Patterns such as trends, clusters and outliers jump out of a scatter plot in a way they never do from a table.

In this lesson you will use ax.scatter, encode extra variables in dot size and color, deal with crowded plots, label individual points and add a trend line. You need the object-oriented pattern and a little NumPy for generating data.

One dot, up to four variables

x Position across.
y Position up.
Size Pass s= for bubble charts.
Color Pass c= and a colormap.

Position is the most accurate channel; use size and color for extras.

1 / 2

scatter versus plot

You can already draw dots with ax.plot(x, y, "o"). So why have ax.scatter? The difference is what each can vary per point.

  • ax.plot creates one Line2D object. All points share one color and size. It is fast, so it is fine for plain dots and for very large arrays.
  • ax.scatter creates one collection, and every point can have its own size, color and transparency.

Use plot when every dot looks the same; use scatter as soon as a variable should control the look of each dot.

Python A first scatter plot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The generator has a fixed seed, so you get the same dots on every run. The upward drift is clear even though each student has random noise on top of the trend.

Size, color and alpha

Useful keyword arguments of scatter:

Argument Meaning
s marker area in points squared (a number, or one per point)
c a single color, or a sequence of numbers mapped through a colormap
cmap the colormap used when c holds numbers
alpha opacity from 0 (invisible) to 1 (solid)
marker marker shape such as "o", "s", "^"
edgecolors, linewidths outline of each marker

Note that s is an area, not a radius. Doubling s doubles the area, which is what readers perceive as "twice as big". If you map data to size, make sure the data is proportional to area, not to diameter.

When c is a list of numbers, Matplotlib maps them to colors, and plt.colorbar (or fig.colorbar) shows the key. Always add the colorbar and label it, or the colors mean nothing.

Python A third variable as color

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

scatter returns a PathCollection, which is the object you hand to fig.colorbar. The colorbar learns the range and colormap from it, so you never have to repeat them.

Overplotting and alpha

With thousands of points, dots land on top of each other and the middle of the cloud becomes a solid blob. You cannot tell 50 points from 5,000. Three fixes work:

  1. Lower alpha (for example 0.2), so dense areas build up color.
  2. Use a smaller marker size.
  3. Aggregate with hexbin or hist2d once the data is huge.
Python Alpha reveals density

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Setting edgecolors="none" removes the marker outlines, which otherwise stay dark and ruin the see-through effect.

Bubble charts

A bubble chart is a scatter plot where marker size carries a third number, such as population or revenue. Scale the sizes so the biggest bubble is large but not enormous, and describe the size meaning somewhere, in the title or in a small legend.

Python
sizes = 30 + 600 * values / values.max()      # area proportional to the value
ax.scatter(x, y, s=sizes, alpha=0.6)

Because s is an area, scaling linearly with the value is the honest choice. Adding a constant (the 30 above) keeps the smallest bubble visible but slightly distorts the ratio, so keep it small or drop it.

Labelling points

To name individual points, loop over them and call ax.annotate (or ax.text). Label only the few points that matter. Labelling all of them creates a mess.

Python Labelled bubbles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

textcoords="offset points" positions the label a fixed number of points from the dot, so the offset stays sensible whatever the axis scale. Annotations get a full lesson in Annotations and Arrows.

Adding a trend line

A fitted line makes the relationship explicit. For a straight line, np.polyfit(x, y, 1) returns the slope and intercept of the least-squares fit. Evaluate it with np.polyval (or compute slope * x + intercept) at sorted x values and draw it with ax.plot.

Python Scatter with a polyfit trend line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The true slope behind the data is 2.2; the fit recovers a value close to it, and noise explains the gap. A trend line shows association, not cause: two variables can move together because a third one drives both. Say so when the chart could be misread, and do not draw a line through data that is clearly curved. Use a higher polynomial degree (np.polyfit(x, y, 2)) or a different model in that case.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When is ax.scatter a better choice than ax.plot(x, y, 'o')?

    plot makes one Line2D with a single style for all points. scatter makes a collection that can vary size, color and alpha per point.
  2. 2. What does the s argument of ax.scatter control?

    s is the marker area, so doubling it doubles the area, and a bubble chart should scale s linearly with the value.
  3. 3. You pass c=values (numbers) and cmap='viridis' to scatter. What must you add so readers can decode the colors?

    A colorbar maps colors back to numbers. The PathCollection returned by scatter supplies its colormap and range.
  4. 4. Which pair of settings best reduces overplotting in a cloud of 4,000 points?

    Low alpha lets overlapping dots accumulate color, so dense regions look darker. Small markers cover less area.
  5. 5. What does np.polyfit(x, y, 1) return?

    With degree 1 it returns the coefficients, highest power first: slope, then intercept. Evaluate them yourself or with np.polyval.

Summary

  • ax.scatter(x, y) draws one marker per point; unlike ax.plot, each marker can have its own size (s), color (c, cmap) and alpha.
  • s is an area. Map data to it linearly for honest bubble charts.
  • Add fig.colorbar(points, ax=ax) whenever color encodes numbers.
  • Fight overplotting with low alpha, small markers or aggregation.
  • Label only the points that matter, with ax.annotate and textcoords="offset points".
  • A trend line from np.polyfit(x, y, 1) shows association, not causation.

Next, count how often values occur in Histograms and Distributions.