Module 2 · Beginner · Matplotlib basics

Line plots with Matplotlib

Line plots in Matplotlib explained: one or many lines, styles and markers, dates on the x-axis, highlighting a line, shading a range, and avoiding spaghetti.

By theprogrammers team · · 5 min read

A line plot joins data points with lines to show how something changes over an ordered sequence, usually time: sales by month, temperature by hour, a share price by day. It's the most common chart in data work, and Matplotlib's ax.plot is its most-used method.

This lesson covers plotting one and several lines, line styles and markers, real dates on the x-axis, highlighting the line that matters, shading ranges, and the mistakes that make line charts hard to read.

A basic line plot

import matplotlib.pyplot as plt
import numpy as np

years = [2019, 2020, 2021, 2022, 2023, 2024, 2025]
users = [1.2, 1.9, 3.1, 4.0, 4.6, 5.8, 7.1]      # millions

fig, ax = plt.subplots()
ax.plot(years, users, marker="o")
ax.set_title("App users by year")
ax.set_xlabel("Year")
ax.set_ylabel("Users (millions)")
plt.show()
A line with circle markers rising from 1.2 million users in 2019 to 7.1 million in 2025.

Use markers when you have a small number of points: they show where the real data is, and that the line between them is just a connection.

If you pass only one list, ax.plot(users), Matplotlib uses 0, 1, 2… for the x-axis.

Several lines on one chart

Call ax.plot once per line, give each a label, and add a legend:

android = [0.8, 1.3, 2.2, 2.9, 3.2, 4.1, 5.0]
ios = [0.4, 0.6, 0.9, 1.1, 1.4, 1.7, 2.1]

fig, ax = plt.subplots()
ax.plot(years, android, marker="o", label="Android")
ax.plot(years, ios, marker="s", label="iOS")
ax.set_title("Users by platform")
ax.set_ylabel("Users (millions)")
ax.legend()
plt.show()
Two lines: Android users rising from 0.8 to 5.0 million and iOS users rising more slowly from 0.4 to 2.1 million, with a legend.

Using different markers as well as colours helps people who can't easily tell the colours apart, and helps when the chart is printed in black and white.

Line styles and the format shortcut

OptionValues
linestyle (ls)"-" solid, "--" dashed, ":" dotted, "-." dash-dot
linewidth (lw)A number, such as 2
marker"o", "s", "^", "D", "x", "."
colorA name, "tab:red", or a hex code "#e76f51"

A short format string combines colour, marker and line style: ax.plot(x, y, "r--") is a red dashed line, and "go-" is green circles joined by a solid line. It's handy for quick charts; named options are clearer in code you'll share.

Smooth curves from a formula

To draw a mathematical curve, give plot many closely spaced x values:

x = np.linspace(0, 2 * np.pi, 200)

fig, ax = plt.subplots()
ax.plot(x, np.sin(x), label="sin(x)")
ax.plot(x, np.cos(x), ls="--", label="cos(x)")
ax.axhline(0, color="grey", lw=0.8)
ax.legend()
plt.show()
A smooth sine curve and a dashed cosine curve from 0 to 2 pi, crossing a thin grey horizontal line at zero.

ax.axhline draws a horizontal reference line across the whole chart; ax.axvline draws a vertical one.

Dates on the x-axis

Real time series use dates. Matplotlib understands them, especially from pandas:

import pandas as pd

dates = pd.date_range("2025-01-01", periods=90, freq="D")
rng = np.random.default_rng(1)
orders = 200 + np.arange(90) * 1.2 + rng.normal(0, 15, 90)

fig, ax = plt.subplots(figsize=(9, 4))
ax.plot(dates, orders)
ax.set_title("Daily orders, January to March 2025")
ax.set_ylabel("Orders")
fig.autofmt_xdate()       # tilt the date labels so they don't overlap
plt.show()
A noisy line of daily orders from January to March 2025 rising from about 200 to about 300, with tilted date labels.

The full guide to dates is in the Matplotlib in depth module; for most charts, passing pandas dates and calling fig.autofmt_xdate() is enough.

Highlight the line that matters

With many lines, a chart becomes "spaghetti": nobody can follow any single line. A powerful fix is to draw everything in grey and only the important line in colour:

cities = {
    "Kanpur": [31, 36, 40, 41, 38, 34],
    "Pune": [33, 36, 38, 36, 30, 28],
    "Delhi": [30, 35, 40, 42, 39, 35],
    "Bengaluru": [32, 34, 34, 33, 29, 28],
    "Chennai": [31, 33, 35, 38, 38, 36],
}
months = ["Feb", "Mar", "Apr", "May", "Jun", "Jul"]

fig, ax = plt.subplots()
for city, temps in cities.items():
    if city == "Kanpur":
        ax.plot(months, temps, color="crimson", lw=3, label=city)
    else:
        ax.plot(months, temps, color="lightgrey", lw=1.5)
ax.set_title("Kanpur's summer is among the hottest")
ax.set_ylabel("Average max temperature (°C)")
ax.legend()
plt.show()
Five city temperature lines from February to July: four in light grey and Kanpur in thick red, peaking at 41 degrees in May.

The title states the message, and the colour points straight at it. (The temperatures are rounded, illustrative values.)

Shade a range

fill_between shades the area between two lines, useful for a range, an uncertainty band, or a target zone:

low = [25, 29, 33, 35, 32, 29]
high = [33, 38, 42, 44, 41, 37]
mid = [(a + b) / 2 for a, b in zip(low, high)]

fig, ax = plt.subplots()
ax.fill_between(months, low, high, alpha=0.3, label="Typical range")
ax.plot(months, mid, color="tab:blue", label="Middle")
ax.legend()
plt.show()
A blue shaded band showing a typical temperature range from February to July, with a darker blue line through its middle.

Mistakes to avoid

MistakeWhy it's a problemFix
Lines between unordered categoriesImplies a trend between unrelated thingsUse a bar chart
Too many linesSpaghetti: nothing can be followedHighlight one; split into small charts
Data not sorted by xThe line zig-zags back and forthSort by x first
Missing values joined silentlyHides gapsLeave NaN, which makes a visible break
Different units on one axisMisleading comparisonsSeparate charts

Practice

  1. Plot these monthly expenses as a dashed line with square markers: [8200, 7900, 9100, 8800, 12500, 9300] for Jan to Jun.
Show the answer
fig, ax = plt.subplots()
ax.plot(["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
        [8200, 7900, 9100, 8800, 12500, 9300], ls="--", marker="s")
ax.set_ylabel("Expenses (₹)")
plt.show()
  1. Plot y = x, y = x² and y = x³ for x from 0 to 2 on one chart, with a legend.
Show the answer
x = np.linspace(0, 2, 100)
fig, ax = plt.subplots()
for power in (1, 2, 3):
    ax.plot(x, x ** power, label=f"x^{power}")
ax.legend()
plt.show()
  1. Your line chart zig-zags wildly back and forth. What's the likely cause?
Show the answer

The data isn't sorted by the x values, so the line jumps between points in the order they appear. Sort by x first, for example with df.sort_values("date").

Interview questions

When should you use a line chart instead of a bar chart?

Use a line chart when the x-axis is continuous or ordered, typically time, and the trend matters. Use a bar chart to compare separate, unordered categories.

How do you plot multiple lines with a legend in Matplotlib?

Call ax.plot once per series with a label, then call ax.legend().

What does fill_between do?

Shades the area between two y-curves (or between a curve and a constant) over the x range, often used for confidence intervals, ranges or highlighting regions.

What to learn next

  1. Compare categories with bar charts in Matplotlib.
  2. Show relationships with scatter plots in Matplotlib.