0Pricing
Pandas & NumPy Academy · Lesson

Line and Scatter Plots

Plot continuous data with ax.plot() and discrete points with ax.scatter(), controlling colour, marker, and line style.

Line and Scatter Plots is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Line and Scatter: Core Plot Types

Line plots connect sequential data points with a line and are ideal for visualising trends over time or continuous functions. Scatter plots draw individual points without connecting lines, making them perfect for exploring relationships between two numeric variables. Both are created on a Matplotlib Axes object: ax.plot() for lines and ax.scatter() for scatter points.

ax.plot() for Line Charts

ax.plot(x, y) draws a line connecting data points in order. Pass x-values as the first argument and y-values as the second. Both can be Python lists, NumPy arrays, or Pandas Series. When only one argument is passed, Matplotlib uses the index (0, 1, 2, ...) as the x-axis automatically. The method returns a list of Line2D Artist objects.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, y)  # basic line plot
ax.set_title('Sine Wave')
ax.set_xlabel('x')
ax.set_ylabel('sin(x)')
# plt.show()
plt.close()

Controlling Line Style and Colour

The most common ax.plot() keyword arguments: color (name, hex, or RGB tuple), linewidth (or lw), linestyle (or ls): '-' solid, '--' dashed, ':' dotted, '-.' dash-dot, marker (shape at each data point), and markersize. Combine linestyle and marker to show both the line and the individual data points simultaneously.

fig, ax = plt.subplots(figsize=(7, 4))

# Solid blue line with circle markers
ax.plot(x, np.sin(x), color='steelblue', lw=2, ls='-',
        marker='o', markersize=4, label='sin(x)')

# Dashed red line
ax.plot(x, np.cos(x), color='crimson', lw=1.5, ls='--', label='cos(x)')

ax.legend()
plt.close()

Plotting Multiple Lines

Call ax.plot() multiple times to overlay several lines on the same Axes. Matplotlib automatically cycles through a default colour palette. Always pass the label keyword for each line so ax.legend() can label them automatically. Place the legend call after all plot calls to ensure all lines are included.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)
dates = pd.date_range('2024-01', periods=12, freq='ME')
fig, ax = plt.subplots(figsize=(8, 4))

for product in ['A', 'B', 'C']:
    sales = np.random.randint(50, 200, 12)
    ax.plot(dates, sales, marker='o', label=f'Product {product}')

ax.set_title('Monthly Sales by Product')
ax.legend()
plt.close()

Plotting Pandas DataFrames Directly

Pandas DataFrames have a .plot() method that creates Matplotlib charts directly. Pass ax=ax to draw on an existing Axes object. df.plot(ax=ax) plots all columns as separate lines using the DataFrame index as the x-axis. You can still apply all Matplotlib customisations on the ax object afterward.

df = pd.DataFrame(
    np.random.randn(12, 3),
    index=pd.date_range('2024', periods=12, freq='ME'),
    columns=['North', 'South', 'West']
).cumsum()

fig, ax = plt.subplots(figsize=(8, 4))
df.plot(ax=ax, linewidth=1.5)
ax.set_title('Cumulative Revenue by Region')
ax.set_ylabel('Revenue (cumulative)')
plt.close()

ax.scatter() for Scatter Plots

ax.scatter(x, y) draws individual points without connecting lines. Unlike ax.plot(), scatter does not assume the data is ordered. Key parameters: c (colour, can be an array for per-point colouring), s (point size, can also be an array), cmap (colourmap for when c is numeric), alpha (transparency 0-1 to handle overplotting).

np.random.seed(42)
x = np.random.randn(100)
y = 2 * x + np.random.randn(100)

fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(x, y, color='steelblue', alpha=0.6, s=40)
ax.set_xlabel('Feature X')
ax.set_ylabel('Target Y')
ax.set_title('Feature vs Target')
plt.close()

Colouring Scatter Points by Category

Pass a numeric array to the c parameter and a cmap colourmap to colour scatter points by a third variable. Add a colourbar with plt.colorbar(scatter_obj) to provide a scale. This technique is called a bubble chart variant when the s (size) parameter is also varied by a fourth variable.

categories = np.random.choice([0, 1, 2], size=100)

fig, ax = plt.subplots(figsize=(6, 5))
scatter = ax.scatter(x, y, c=categories, cmap='Set1',
                     alpha=0.7, s=60, edgecolors='none')
fig.colorbar(scatter, ax=ax, label='Category')
ax.set_title('Scatter Coloured by Category')
plt.close()

Adding a Trend Line

A scatter plot with a fitted trend line communicates both the individual data points and the overall pattern. Use np.polyfit(x, y, 1) to compute a linear fit, evaluate it with np.poly1d(coeffs)(x_range), and overlay the result with ax.plot() on top of the scatter. The trend line should be thinner and styled differently to distinguish it from data points.

fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(x, y, alpha=0.4, s=30, color='steelblue', label='Data')

# Fit and plot linear trend line
coeffs = np.polyfit(x, y, 1)
x_line = np.linspace(x.min(), x.max(), 100)
y_line = np.poly1d(coeffs)(x_line)
ax.plot(x_line, y_line, color='red', lw=2, label='Linear fit')

ax.legend()
ax.set_title('Scatter with Trend Line')
plt.close()

Shading Confidence Bands with fill_between

ax.fill_between(x, y_lower, y_upper) fills the area between two curves. This is commonly used to show confidence intervals around a mean line, standard deviation bands, or min/max envelopes. Pass alpha to make the shading semi-transparent so the underlying data remains visible.

x_range = np.linspace(0, 2 * np.pi, 100)
mean = np.sin(x_range)
upper = mean + 0.2
lower = mean - 0.2

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x_range, mean, color='steelblue', lw=2, label='Mean')
ax.fill_between(x_range, lower, upper,
                color='steelblue', alpha=0.2, label='±0.2 band')
ax.legend()
ax.set_title('Line with Confidence Band')
plt.close()

Axis Limits and Grid Lines

Control the visible range with ax.set_xlim(min, max) and ax.set_ylim(min, max). Enable grid lines with ax.grid(True). Customise the grid with keyword arguments: linestyle, linewidth, alpha. A subtle grid with alpha=0.3 aids reading exact values without cluttering the chart. Call ax.set_axisbelow(True) to draw the grid behind data points.

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, np.sin(x), 'b-', lw=2)

ax.set_xlim(0, 2 * np.pi)
ax.set_ylim(-1.2, 1.2)
ax.grid(True, linestyle='--', alpha=0.5)
ax.set_axisbelow(True)  # grid behind data
ax.set_title('Sine with Grid')
plt.close()

Alpha and Overplotting

When many data points overlap in the same region of a scatter plot, individual points become invisible — this is called overplotting. The simplest fix is to reduce opacity with alpha (0.0 = fully transparent, 1.0 = fully opaque). Set alpha=0.3 or lower so that dense regions appear darker (because multiple semi-transparent points stack up) while sparse regions remain light. For very large datasets (millions of points), consider hexbin or kernel density estimates instead.

np.random.seed(1)
x_dense = np.random.randn(1000)
y_dense = np.random.randn(1000)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))

# Without alpha: overplotting hides density
ax1.scatter(x_dense, y_dense, s=10)
ax1.set_title('No alpha (overplotted)')

# With alpha: density visible
ax2.scatter(x_dense, y_dense, s=10, alpha=0.2)
ax2.set_title('alpha=0.2 (density visible)')

plt.tight_layout()
plt.close()

Quick Check

Test your understanding of line and scatter plots in Matplotlib from this lesson.

Lesson Recap

In this lesson you learned: ax.plot() creates line charts with full control over colour, line style, and markers; ax.scatter() creates scatter plots with per-point colour and size via c and s; ax.fill_between() adds confidence bands; and ax.grid() adds grid lines for readability. Next up we create bar charts and histograms to visualise categorical and distributional data.

Frequently asked questions

Is the “Line and Scatter Plots” lesson free?

Yes — the full text of “Line and Scatter Plots” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.

What will I learn in “Line and Scatter Plots”?

Plot continuous data with ax.plot() and discrete points with ax.scatter(), controlling colour, marker, and line style. You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Pandas & NumPy Academy?

No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Line and Scatter Plots” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Pandas & NumPy Academy lesson?

Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Figure and Axes Architecture
  2. Line and Scatter Plots
  3. Bar Charts and Histograms
  4. Labels, Titles, and Saving Figures
← Back to Pandas & NumPy Academy