How do I draw a line chart with matplotlib?

Draw two stock price indices on one set of axes, label their lines and axes, and save the figure as a PNG.

After this lesson, you can plot two stock price indices that start at 100, read which stock has gained more since the start, and save the chart for a report.

How do I put both lines on one chart?

fig, ax = plt.subplots() creates a figure and its plotting area, and ax.plot(dates, prices[ticker], label=ticker) adds one line per stock to that area, so a loop over the tickers puts both lines on the same chart. On 4 March, AAA’s line ends at 103 above BBB’s at 101, after BBB led on 3 March.

The made-up price indices of AAA and BBB start at 100 points on 2 March 2026, so 103 means a price gain of 3% since then, without dividends. ax.set() sets the title and the two axis labels in one call, ax.legend() shows the line names, and fig.tight_layout() fits the text into the figure. The dates are text, so matplotlib spaces them evenly in row order, and a weekend between two dates would take no space. The insider buying backtest compares a portfolio with its benchmark in the same kind of chart.

The following box builds the prices and draws both lines.

import matplotlib.pyplot as plt
import pandas as pd

prices = pd.DataFrame({"date": ["2 Mar", "3 Mar", "4 Mar"], "AAA": [100, 99, 103], "BBB": [100, 102, 101]})
fig, ax = plt.subplots(figsize=(6, 3))
for ticker in ["AAA", "BBB"]:
    ax.plot(prices["date"], prices[ticker], label=ticker)
ax.set(title="AAA and BBB", xlabel="March 2026", ylabel="Price index (points)")
ax.legend()
ax.grid(True)
fig.tight_layout()
plt.show()

How do I save the chart for a report?

fig.savefig(path) writes the figure to a file in the format of the file’s extension, so prices.png gives a PNG. .is_file() confirms that the file exists.

Path("line_chart_demo") names a folder, .mkdir(exist_ok=True) creates it or accepts it if it exists, and / joins the folder and the file name.

The following box saves the chart and checks the file.

from pathlib import Path

folder = Path("line_chart_demo")
folder.mkdir(exist_ok=True)
fig.savefig(folder / "prices.png")
print((folder / "prices.png").is_file())
True

Your turn

Draw BBB’s line for 3 and 4 March and print the two rows you plot. You should see BBB fall from 102 to 101.

.loc[1:2] takes the rows labelled 1 and 2.

two_days = prices.loc[1:2, ["date", "BBB"]]
print(two_days)
fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(two_days["date"], two_days["BBB"], label="BBB")
ax.set(title="BBB", xlabel="March 2026", ylabel="Price index (points)")
ax.legend()
plt.show()
    date  BBB
1  3 Mar  102
2  4 Mar  101