Module 1 · Beginner · Getting started with Python charts

Your first chart in Python, step by step

Make your first chart in Python with Matplotlib step by step: plot a line, add a title and labels, change colours and markers, plot two lines, save it.

By theprogrammers team · · 6 min read

In this lesson you'll make your first real chart in Python, starting from two lists of numbers and finishing with a labelled, styled chart saved as an image you could put in a report. Each step adds one thing, so you can see exactly what each line of code does.

You need Python with Matplotlib installed. The quickest way is Google Colab, which has it ready with nothing to install; for a setup on your own computer, follow set up a machine learning environment in Python. If you've never used Python lists before, start with Python lists.

The data

We'll chart the average monthly maximum temperature in a city, in °C:

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
temps = [22, 26, 32, 38, 41, 39, 34, 33, 33, 32, 28, 23]

These are rounded, typical values for a city in north India. The question our chart answers: how does temperature change through the year? That's change over time, so a line chart is the right choice, as explained in how to choose the right chart.

Step 1: import Matplotlib

import matplotlib.pyplot as plt

pyplot is the part of Matplotlib for making charts, and plt is the short name everyone uses.

Step 2: plot the line

plt.plot(months, temps)
plt.show()
A plain blue line chart of temperature by month, rising from about 22 in January to a peak near 41 in May, then falling back to about 23 in December. It has no title or axis labels.

That's a chart. plt.plot(x, y) takes the values for the horizontal axis first and the vertical axis second; they must have the same length. plt.show() displays it. (In Jupyter or Colab, charts appear even without plt.show(), but it's a good habit, and it's required in a normal .py script.)

You can already see the story: a steep climb to a May peak, a dip as the monsoon arrives, then cooling towards winter. But a reader wouldn't know what the numbers mean.

Step 3: add a title and axis labels

plt.plot(months, temps)
plt.title("Average maximum temperature by month")
plt.xlabel("Month")
plt.ylabel("Temperature (°C)")
plt.show()
The same line chart, now with the title "Average maximum temperature by month", the x-axis labelled Month and the y-axis labelled Temperature in degrees Celsius.

Every chart you show anyone needs a title that says what it shows, and axis labels with units. It's the cheapest improvement you'll ever make.

Step 4: style the line

plot accepts options to change the look:

plt.plot(months, temps, color="darkorange", marker="o",
         linewidth=2, markersize=6)
plt.title("Average maximum temperature by month")
plt.xlabel("Month")
plt.ylabel("Temperature (°C)")
plt.grid(alpha=0.3)
plt.show()
The temperature line chart in dark orange with a round marker at each month and light gridlines behind it.
OptionDoesExamples
colorLine colour"darkorange", "tab:blue", "#1f77b4"
markerA symbol at each point"o" circle, "s" square, "^" triangle
linestyleLine pattern"-" solid, "--" dashed, ":" dotted
linewidthThickness2
markersizeMarker size6

Markers help readers see that the data is 12 separate months, not a continuous measurement. plt.grid(alpha=0.3) adds faint gridlines; alpha sets transparency, from 0 (invisible) to 1 (solid).

Step 5: compare two lines

Add the minimum temperatures, give each line a label, and call plt.legend() to show which is which:

mins = [8, 11, 16, 22, 27, 29, 27, 26, 25, 19, 13, 9]

plt.plot(months, temps, marker="o", color="darkorange", label="Maximum")
plt.plot(months, mins, marker="o", color="steelblue", label="Minimum")
plt.title("Average daily temperature range by month")
plt.xlabel("Month")
plt.ylabel("Temperature (°C)")
plt.legend()
plt.grid(alpha=0.3)
plt.show()
Two lines: an orange maximum temperature line peaking near 41 in May and a blue minimum temperature line peaking near 29 in June, both lowest in January and December, with a legend labelling Maximum and Minimum.

Each call to plt.plot adds another line to the same chart, until plt.show() displays it. Now there's a second insight: the gap between day and night is widest in spring and narrowest in the monsoon.

Step 6: save it as an image

Use plt.savefig before plt.show(). Showing a chart can clear it, so saving afterwards may give you a blank image:

plt.plot(months, temps, marker="o", color="darkorange", label="Maximum")
plt.plot(months, mins, marker="o", color="steelblue", label="Minimum")
plt.title("Average daily temperature range by month")
plt.xlabel("Month")
plt.ylabel("Temperature (°C)")
plt.legend()
plt.grid(alpha=0.3)
plt.savefig("temperature.png", dpi=200, bbox_inches="tight")
plt.show()
  • dpi=200 makes a sharp, high-resolution image, good for reports and slides.
  • bbox_inches="tight" trims empty space around the chart so labels aren't cut off.
  • Change the extension to .svg or .pdf for an image that stays sharp at any size.

The file appears in the same folder as your script or notebook.

The complete program

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
temps = [22, 26, 32, 38, 41, 39, 34, 33, 33, 32, 28, 23]
mins = [8, 11, 16, 22, 27, 29, 27, 26, 25, 19, 13, 9]

plt.plot(months, temps, marker="o", color="darkorange", label="Maximum")
plt.plot(months, mins, marker="o", color="steelblue", label="Minimum")
plt.title("Average daily temperature range by month")
plt.xlabel("Month")
plt.ylabel("Temperature (°C)")
plt.legend()
plt.grid(alpha=0.3)
plt.savefig("temperature.png", dpi=200, bbox_inches="tight")
plt.show()

Common problems

ProblemCauseFix
ModuleNotFoundError: No module named 'matplotlib'Not installed in this Pythonpip install matplotlib in the same environment
ValueError: x and y must have same first dimensionThe two lists have different lengthsCheck len(months) and len(temps)
No chart window appears in a scriptMissing plt.show()Add it at the end
The saved image is blanksavefig after showSave first, then show
The legend is emptyNo label= on the linesAdd label="..." to each plot

Practice

  1. Plot these weekly study hours as a line chart with a title and axis labels: weeks 1 to 6, hours [5, 7, 6, 9, 12, 10].
Show the answer
weeks = [1, 2, 3, 4, 5, 6]
hours = [5, 7, 6, 9, 12, 10]
plt.plot(weeks, hours, marker="o")
plt.title("Study hours per week")
plt.xlabel("Week")
plt.ylabel("Hours")
plt.show()
  1. Make the line dashed and green, with square markers.
Show the answer
plt.plot(weeks, hours, color="green", linestyle="--", marker="s")
plt.show()
  1. Save your chart as study.svg. Why might you choose SVG instead of PNG?
Show the answer

plt.savefig("study.svg", bbox_inches="tight") before plt.show(). SVG is a vector format, so it stays perfectly sharp at any zoom level, which is ideal for websites and printed documents.

Interview questions

How do you create a basic line chart in Matplotlib?

Import matplotlib.pyplot as plt, call plt.plot(x, y), add plt.title, plt.xlabel and plt.ylabel, and call plt.show() to display it, or plt.savefig() before showing to save it.

Why should savefig be called before show?

plt.show() displays and then can close or clear the current figure, especially in scripts, so a later savefig may write an empty image.

What do dpi and bbox_inches="tight" do in savefig?

dpi sets the resolution in dots per inch, so a higher value means a sharper, larger image. bbox_inches="tight" crops the saved image to the chart's content, removing extra whitespace and preventing labels from being cut off.

What to learn next

  1. Name every part of a chart in anatomy of a chart: figure, axes, ticks and legends.
  2. Go deeper on lines in line plots with Matplotlib.