Line charts make ordered values easier to compare across time, sequence, or another meaningful x-axis. In Matplotlib, a line chart starts with paired x and y values and an Axes.plot() call that connects the points on one set of axes.
The object-oriented interface keeps the figure and axes explicit. plt.subplots() returns the Figure and Axes objects, ax.plot() draws the series, and fig.savefig() writes the finished figure without relying on notebook display state.
The sample uses six weekly values and saves a PNG so the output can be checked outside an interactive session. Replace the labels and values with your own ordered data after the saved file shows the connected line, markers, axis labels, and title.
Related: How to create a scatter plot in Matplotlib
Related: How to set plot colors in Matplotlib
Related: How to add a legend in Matplotlib
Steps to create a Matplotlib line chart:
- Save the line chart script as create_line_chart.py.
- create_line_chart.py
from pathlib import Path import matplotlib.pyplot as plt weeks = ["Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6"] tickets_closed = [42, 38, 47, 55, 61, 58] fig, ax = plt.subplots(layout="constrained") ax.plot(weeks, tickets_closed, marker="o", linewidth=2) ax.set_title("Support tickets closed by week") ax.set_xlabel("Week") ax.set_ylabel("Tickets closed") ax.grid(True, axis="y", alpha=0.3) output = Path("support-tickets-line-chart.png") fig.savefig(output, dpi=160) plt.close(fig) print(f"points: {len(tickets_closed)}") print(f"title: {ax.get_title()}") print(f"x label: {ax.get_xlabel()}") print(f"y label: {ax.get_ylabel()}") print(f"saved: {output}") print(f"bytes: {output.stat().st_size}")
layout=“constrained” leaves room for labels and the title while the figure is saved.
- Run the script from the Python environment that has Matplotlib installed.
$ python create_line_chart.py points: 6 title: Support tickets closed by week x label: Week y label: Tickets closed saved: support-tickets-line-chart.png bytes: 54371
The byte count can change with Matplotlib, font, backend, or DPI differences. A nonzero byte count and the expected filename confirm that the PNG was written.
- Open support-tickets-line-chart.png and confirm the plotted result.
The image should show one connected line with circular markers across the six week labels, plus the Week and Tickets closed axis labels.
- Replace the sample lists with your own ordered x and y values.
weeks = ["Week 1", "Week 2", "Week 3", "Week 4"] tickets_closed = [42, 38, 47, 55]
The x and y sequences must have the same length because each x value is paired with one y value.
- Remove the sample files when they were created only for testing.
$ rm create_line_chart.py support-tickets-line-chart.png
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.