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()
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()
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
| Option | Values |
|---|---|
linestyle (ls) | "-" solid, "--" dashed, ":" dotted, "-." dash-dot |
linewidth (lw) | A number, such as 2 |
marker | "o", "s", "^", "D", "x", "." |
color | A 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()
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()
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()
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()
Mistakes to avoid
| Mistake | Why it's a problem | Fix |
|---|---|---|
| Lines between unordered categories | Implies a trend between unrelated things | Use a bar chart |
| Too many lines | Spaghetti: nothing can be followed | Highlight one; split into small charts |
| Data not sorted by x | The line zig-zags back and forth | Sort by x first |
| Missing values joined silently | Hides gaps | Leave NaN, which makes a visible break |
| Different units on one axis | Misleading comparisons | Separate charts |
Practice
- 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()
- 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()
- 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
- Compare categories with bar charts in Matplotlib.
- Show relationships with scatter plots in Matplotlib.