To make a line plot in Matplotlib, call ax.plot(x, y). Call it once per line to draw multiple lines on the same axes, give each one a label, and call ax.legend(). The look of each line is set with color, linestyle, linewidth, and marker.
Quick Example
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(12)
years = np.arange(2010, 2026)
t = years - 2010
solar = 2 * np.exp(0.22 * t) + rng.normal(0, 1.0, t.size)
wind = 12 + 4.5 * t + rng.normal(0, 2.5, t.size)
hydro = 48 + rng.normal(0, 3.0, t.size)
fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
ax.plot(years, solar, color="#f59e0b", linewidth=2.5, marker="o", label="Solar")
ax.plot(years, wind, color="#0891b2", linewidth=2.5, marker="s", label="Wind")
ax.plot(years, hydro, color="#4f46e5", linewidth=2.5, linestyle="--", label="Hydro")
ax.set_title("Renewable generation by source (TWh)")
ax.set_xlabel("Year")
ax.set_ylabel("TWh")
ax.legend()
plt.show()

In this sample data, wind climbs from 14 to 78 TWh and passes the flat hydro line in 2019. Solar starts at 2 TWh and only overtakes hydro in 2025. The code targets Matplotlib 3.10 and 3.11.
The Line Arguments in ax.plot
| Argument | Short name | What it sets | Default |
|---|---|---|---|
color |
c |
Line color | Next color in the cycle |
linestyle |
ls |
Solid, dashed, dotted, or a custom pattern | "-" |
linewidth |
lw |
Width in points | 1.5 |
marker |
Symbol drawn at each data point | none | |
markersize |
ms |
Marker size in points | 6 |
alpha |
Opacity from 0 to 1 | 1 |
|
label |
Text used by ax.legend() |
none | |
zorder |
Draw order; higher is on top | 2 for lines |
There is also a format string shortcut: ax.plot(years, wind, "s--") means square markers with a dashed line, and "o" on its own draws markers with no line. It's handy in a notebook, but keyword arguments are easier to read in code you'll keep.
Matplotlib Line Styles
linestyle accepts four named patterns, "-", "--", "-.", and ":" (also spelled "solid", "dashed", "dashdot", and "dotted"). For anything else, pass a tuple (offset, (on, off, on, off, ...)), where the lengths are measured in multiples of the line width by default.
fig, ax = plt.subplots(figsize=(8, 4), layout="constrained")
styles = [("-", '"-" solid'), ("--", '"--" dashed'), ("-.", '"-." dash-dot'),
(":", '":" dotted'), ((0, (8, 3)), "(0, (8, 3)) long dash"),
((0, (5, 2, 1, 2, 1, 2)), "(0, (5, 2, 1, 2, 1, 2)) dash-dot-dot")]
for i, (style, name) in enumerate(styles):
y = len(styles) - i
ax.plot([0, 1], [y, y], linestyle=style, color="#1f2937", linewidth=2.5)
ax.text(1.04, y, name, va="center", family="monospace", fontsize=11)
ax.set_xlim(0, 1.75)
ax.set_ylim(0.4, len(styles) + 0.6)
ax.axis("off")
ax.set_title("Matplotlib linestyle values")
plt.show()

To draw reference lines rather than data, axhline and axvline are simpler than plot. See Matplotlib Horizontal and Vertical Lines.
Plot Multiple Lines in a Loop and Label the Line Ends
With more than two or three series, loop over a dictionary. ax.plot returns a list of lines, so (line,) = ... unpacks the one you just drew and line.get_color() lets the text match it. Labels at the end of each line save the reader from matching colors against a legend.
hours = np.arange(24)
daily = np.sin((hours - 9) / 24 * 2 * np.pi)
regions = {"us-east": (120, 38), "eu-west": (95, 22), "ap-south": (70, 12), "sa-east": (45, 6)}
traffic = {name: base + amp * np.roll(daily, shift) + rng.normal(0, 2, 24)
for shift, (name, (base, amp)) in zip([0, -5, -9, 1], regions.items())}
fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
for name, values in traffic.items():
(line,) = ax.plot(hours, values, linewidth=2, label=name)
ax.annotate(name, xy=(hours[-1], values[-1]), xytext=(6, 0),
textcoords="offset points", va="center", color=line.get_color())
ax.set_title("Requests per second by region")
ax.set_xlabel("Hour of day (UTC)")
ax.set_xlim(0, 23)
ax.spines[["top", "right"]].set_visible(False)
plt.show()

xytext=(6, 0) with textcoords="offset points" nudges each label 6 points to the right of the last data point, whatever the data scale is. If two series end at nearly the same value the labels will collide, and a legend outside the plot is the better choice.
Highlight One Line Among Many
Twelve colored lines are unreadable. Draw all of them in light gray, then plot the one you care about again on top. Passing a 2D array to ax.plot draws one line per column.
weeks = np.arange(1, 53)
stores = rng.normal(0.4, 2.2, (52, 12)).cumsum(axis=0) + 100
stores[:, 7] = 100 + 0.9 * weeks + rng.normal(0, 1.5, 52)
fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
ax.plot(weeks, stores, color="#cbd5e1", linewidth=1)
ax.plot(weeks, stores[:, 7], color="#be123c", linewidth=2.8)
ax.annotate("Store 8", xy=(52, stores[-1, 7]), xytext=(6, 0), textcoords="offset points",
va="center", color="#be123c", fontweight="bold")
ax.set_title("Weekly sales index: Store 8 vs the other 11 stores")
ax.set_xlabel("Week")
ax.set_xlim(1, 52)
ax.spines[["top", "right"]].set_visible(False)
plt.show()

Store 8 finishes the year at 146, just ahead of the best of the other stores at 143.
Handle Missing Values: Gaps in a Line
Matplotlib breaks a line wherever y is NaN. That's usually what you want for a sensor dropout, since a straight segment would suggest readings you don't have. If you do want to join the gap, plot the non-missing points as a second, fainter line underneath.
minutes = np.arange(120)
temp = 21 + 2.5 * np.sin(minutes / 19) + rng.normal(0, 0.15, 120)
temp[40:55] = np.nan
temp[88:96] = np.nan
ok = ~np.isnan(temp)
fig, axes = plt.subplots(1, 2, figsize=(9, 3.4), sharey=True, layout="constrained")
axes[0].plot(minutes, temp, color="#15803d", linewidth=2)
axes[0].set_title("NaN leaves a gap")
axes[1].plot(minutes, temp, color="#15803d", linewidth=2)
axes[1].plot(minutes[ok], temp[ok], color="#15803d", linewidth=1.2, linestyle=":", zorder=1)
axes[1].set_title("Dotted bridge over the gaps")
for ax in axes:
ax.set_xlabel("Minute")
axes[0].set_ylabel("Sensor temperature (°C)")
plt.show()

A value that sits alone between two NaNs won't show up at all, because a line needs two neighboring points. Add marker="." if your data is patchy.
Plot Lines from a pandas DataFrame
Pass the index as x and the whole DataFrame as y to get one line per column. label=df.columns names them all at once for the legend.
import matplotlib.dates as mdates
import pandas as pd
df = pd.DataFrame(
{"Mobile": rng.normal(1.2, 1.0, 90).cumsum() + 50,
"Desktop": rng.normal(0.2, 1.0, 90).cumsum() + 80,
"Tablet": rng.normal(0.0, 0.5, 90).cumsum() + 25},
index=pd.date_range("2026-01-01", periods=90, freq="D"),
)
fig, ax = plt.subplots(figsize=(8, 4.2), layout="constrained")
ax.plot(df.index, df, linewidth=1.8, label=df.columns)
ax.set_title("Daily orders by device")
ax.legend(ncols=3)
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))
plt.show()

Mobile orders pass desktop in early February. df.plot() produces a similar chart in one line, as shown in Plot Multiple Columns on the Same Line Chart in Pandas. For more control over the date labels, see custom date formatting.
plt.plot vs ax.plot
Both draw the same line. plt.plot() targets whichever axes is "current", which is fine for a quick single chart. ax.plot() names the axes it draws on, so it keeps working when you add subplots or move the plotting code into a function. Use ax.plot() in anything longer than a few lines.
Practical Tips
- Distinguish lines by style or marker as well as color, so the chart survives grayscale printing and color-vision differences.
- With hundreds of points, markers merge into a thick band. Drop them, or use
markevery=10to draw every tenth one. - If your x values aren't sorted, the line will zigzag back and forth. Sort first with
df.sort_values("x"), or use a scatter plot. - To show uncertainty around a line, use
fill_between, covered in Line Chart with Confidence Interval in Python.