ZetCode

Python Matplotlib

last modified November 18, 2026 Python 3.15

In this article we show how to create charts in Python with Matplotlib. We create line charts, scatter charts, bar charts, pie charts, and histograms, put several charts in one figure, and save the charts to files.

Matplotlib

Matplotlib is a Python library for creating static, animated, and interactive charts. It can be used in Python scripts, the Python and IPython shells, Jupyter notebooks, web application servers, and GUI toolkits. Libraries such as pandas and seaborn use Matplotlib to draw their charts.

Matplotlib has two interfaces. The pyplot module provides MATLAB-like functions such as plt.plot and plt.title that act on the current chart. The object-oriented interface works with explicit Figure and Axes objects. The Matplotlib documentation recommends the object-oriented interface for anything beyond quick interactive work, and we use it in this article.

A Figure is the whole image: a window or a file. An Axes is a single chart inside the figure, with its own x and y axis, title, and data. A figure can contain several axes.

Installation

Matplotlib is an external library. It depends on NumPy, which we also use directly in some examples.

version.py
import matplotlib
import numpy as np

print(matplotlib.__version__)
print(np.__version__)

After installing the library with pip install matplotlib, we print the versions of Matplotlib and NumPy.

$ python version.py
3.11.2
2.5.5

First chart

We start with a simple line chart.

first.py
import matplotlib.pyplot as plt

years = [2019, 2020, 2021, 2022, 2023, 2024, 2025]
users = [120, 180, 260, 310, 400, 520, 610]

fig, ax = plt.subplots()

ax.plot(years, users)
ax.set_title('Registered users')
ax.set_xlabel('Year')
ax.set_ylabel('Users (thousands)')

fig.savefig('first.png')

The example draws the growth of registered users over the years.

import matplotlib.pyplot as plt

By convention, the pyplot module is imported as plt.

fig, ax = plt.subplots()

The subplots function creates a figure and a single axes object.

ax.plot(years, users)
ax.set_title('Registered users')
ax.set_xlabel('Year')
ax.set_ylabel('Users (thousands)')

The plot method draws a line through the points. Then we set the title and the axis labels.

fig.savefig('first.png')

The savefig method writes the figure to a file; the format is taken from the file extension. To display the chart in a window instead, we call plt.show(), which blocks until the window is closed. In Jupyter notebooks, the charts are displayed automatically.

Line chart
Figure: Line chart

Scatter chart

A scatter chart displays the values of two variables as points in Cartesian coordinates.

scatter.py
import matplotlib.pyplot as plt

x_axis = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y_axis = [5, 16, 34, 56, 32, 56, 32, 12, 76, 89]

fig, ax = plt.subplots()

ax.scatter(x_axis, y_axis, color='darkblue', marker='x', label='item 1')

ax.set_title('Prices over 10 years')
ax.set_xlabel('Time (years)')
ax.set_ylabel('Price (dollars)')
ax.grid(True)
ax.legend()

fig.savefig('scatter.png')

The example draws the prices of an item over ten years.

ax.scatter(x_axis, y_axis, color='darkblue', marker='x', label='item 1')

The scatter method draws the chart. It accepts the data for the x and y axes, the color and the shape of the markers, and the label used in the legend.

ax.grid(True)
ax.legend()

The grid method shows the grid lines, and the legend method places a legend on the axes. The legend uses the labels of the drawn data.

Scatter chart
Figure: Scatter chart

Two data sets

In the next example, we add another data set to the chart.

scatter2.py
import matplotlib.pyplot as plt

years = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
prices1 = [5, 16, 34, 56, 32, 56, 32, 12, 76, 89]
prices2 = [53, 6, 46, 36, 15, 64, 73, 25, 82, 9]

fig, ax = plt.subplots()

ax.scatter(years, prices1, color='darkblue', marker='x', label='item 1')
ax.scatter(years, prices2, color='darkred', marker='o', label='item 2')

ax.set_title('Prices over 10 years')
ax.set_xlabel('Time (years)')
ax.set_ylabel('Price (dollars)')
ax.grid(True)
ax.legend()

fig.savefig('scatter2.png')

We call the scatter method for each data set. The sets are distinguished by the colour and the shape of the markers.

Scatter chart with two data sets
Figure: Scatter chart with two data sets

Line chart

A line chart displays information as a series of data points connected by straight line segments. With enough points, it draws smooth curves.

linechart.py
import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2.5 * np.pi * t)

fig, ax = plt.subplots()

ax.plot(t, s)

ax.set_xlabel('time (s)')
ax.set_ylabel('voltage (mV)')
ax.set_title('Sine wave')
ax.grid(True)

fig.savefig('linechart.png')

The example displays a sine wave.

t = np.arange(0.0, 3.0, 0.01)
s = np.sin(2.5 * np.pi * t)

The NumPy arange function returns an array of evenly spaced values in the given interval; we have 300 points between 0 and 3. The sin function is applied to the whole array at once.

Sine wave line chart
Figure: Sine wave line chart

Line styles and markers

Several lines can share one axes. Each line can have its own colour, line style, and markers.

lines.py
import matplotlib.pyplot as plt

months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
bratislava = [0, 2, 7, 12, 17, 20]
oslo = [-4, -4, 0, 5, 11, 15]
rome = [8, 9, 12, 15, 19, 23]

fig, ax = plt.subplots(figsize=(7, 4.5))

ax.plot(months, bratislava, 'o-', label='Bratislava')
ax.plot(months, oslo, 's--', color='tab:green', label='Oslo')
ax.plot(months, rome, marker='^', linestyle=':', linewidth=2, label='Rome')

ax.axhline(0, color='gray', linewidth=0.8)
ax.set_title('Average temperature')
ax.set_ylabel('°C')
ax.legend(loc='upper left')

fig.savefig('lines.png')

We compare average temperatures in three cities. Matplotlib accepts strings on the x axis and treats them as categories.

ax.plot(months, bratislava, 'o-', label='Bratislava')
ax.plot(months, oslo, 's--', color='tab:green', label='Oslo')
ax.plot(months, rome, marker='^', linestyle=':', linewidth=2, label='Rome')

A format string such as 'o-' sets the marker and the line style in a short form: circles with a solid line, squares with a dashed line. The keyword arguments do the same in a more readable way. Lines without an explicit colour get the next colour of the default cycle.

ax.axhline(0, color='gray', linewidth=0.8)

The axhline method draws a horizontal line across the axes; here it marks the freezing point.

Line chart with three lines
Figure: Line chart with three lines

Bar chart

A bar chart presents categorical data with rectangular bars whose lengths are proportional to the values that they represent.

barchart.py
import matplotlib.pyplot as plt

countries = ['USA', 'China', 'Japan', 'Australia', 'France', 'Netherlands']
golds = [40, 40, 20, 18, 16, 15]

fig, ax = plt.subplots(figsize=(7, 4.5))

bars = ax.bar(countries, golds, color='goldenrod')
ax.bar_label(bars, padding=3)

ax.set_title('Olympic gold medals in Paris 2024')
ax.set_ylabel('Gold medals')
ax.set_ylim(0, 45)

fig.savefig('barchart.png')

The example shows the countries with the most gold medals at the Paris 2024 Olympic Games.

fig, ax = plt.subplots(figsize=(7, 4.5))

The figsize parameter sets the size of the figure in inches. The default is 6.4 by 4.8 inches at 100 dots per inch.

bars = ax.bar(countries, golds, color='goldenrod')
ax.bar_label(bars, padding=3)

The bar method draws the bars and returns a container with them. The bar_label method writes the values above the bars.

Bar chart
Figure: Bar chart

Horizontal bar chart

Horizontal bars are better for long category names or many categories.

barh.py
import matplotlib.pyplot as plt

langs = ['Python', 'JavaScript', 'Java', 'C#', 'Go', 'Rust']
votes = [14, 9, 5, 4, 7, 6]

votes, langs = zip(*sorted(zip(votes, langs)))

fig, ax = plt.subplots()

ax.barh(langs, votes, color='steelblue')
ax.set_xlabel('Votes')
ax.set_title('Favourite language in our team')

fig.tight_layout()
fig.savefig('barh.png')

We sort the data by the number of votes before plotting. The barh method draws the bars from the bottom up, so the largest value is at the top. The tight_layout method adjusts the margins so that the labels fit in the figure.

Horizontal bar chart
Figure: Horizontal bar chart

Pie chart

A pie chart is a circular chart divided into slices to illustrate numerical proportion.

piechart.py
import matplotlib.pyplot as plt

labels = ['Oranges', 'Pears', 'Plums', 'Blueberries']
quantity = [38, 45, 24, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']

fig, ax = plt.subplots()

ax.pie(quantity, labels=labels, colors=colors, autopct='%1.1f%%',
       startangle=90, explode=[0, 0.1, 0, 0])
ax.set_title('Fruit sold')

fig.savefig('piechart.png')

The example creates a pie chart of fruit sold.

ax.pie(quantity, labels=labels, colors=colors, autopct='%1.1f%%',
       startangle=90, explode=[0, 0.1, 0, 0])

The pie method computes the proportions from the quantities. The autopct format string writes the percentages inside the wedges. The startangle rotates the start of the first wedge to the top, and explode moves the second wedge out of the pie by a tenth of the radius. Pie charts are drawn as circles by default.

Pie chart
Figure: Pie chart

Histogram

A histogram shows the distribution of numerical data. The range of values is divided into bins, and the height of each bar is the number of values in the bin.

histogram.py
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(42)
heights = rng.normal(loc=172, scale=8, size=1000)

print(f'mean: {heights.mean():.1f}, std: {heights.std():.1f}')

fig, ax = plt.subplots()

counts, edges, _ = ax.hist(heights, bins=25, color='tab:purple', edgecolor='white')
ax.axvline(heights.mean(), color='black', linestyle='--', label='mean')

ax.set_title('Height of 1000 people')
ax.set_xlabel('Height (cm)')
ax.set_ylabel('Count')
ax.legend()

print(f'largest bin: {counts.max():.0f} people between {edges[counts.argmax()]:.1f} '
      f'and {edges[counts.argmax() + 1]:.1f} cm')

fig.savefig('histogram.png')

We generate the heights of 1000 people from a normal distribution with a mean of 172 cm. The random generator is seeded, so every run produces the same data.

counts, edges, _ = ax.hist(heights, bins=25, color='tab:purple', edgecolor='white')

The hist method divides the data into 25 bins and draws the bars. It also returns the counts and the bin edges, which we use to print the largest bin.

ax.axvline(heights.mean(), color='black', linestyle='--', label='mean')

A vertical dashed line marks the mean. The program also prints statistics of the generated data, shown after the chart.

Histogram
Figure: Histogram
$ python histogram.py
mean: 171.8, std: 7.9
largest bin: 137 people between 173.4 and 175.6 cm

Subplots

A figure can contain a grid of axes. The subplots function creates them in one call.

subplots.py
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 200)

fig, axs = plt.subplots(2, 2, figsize=(8, 6), layout='constrained')

axs[0, 0].plot(x, np.sin(x))
axs[0, 0].set_title('sin(x)')

axs[0, 1].plot(x, np.cos(x), color='tab:orange')
axs[0, 1].set_title('cos(x)')

axs[1, 0].bar(['a', 'b', 'c', 'd'], [3, 7, 2, 5], color='tab:green')
axs[1, 0].set_title('bar')

axs[1, 1].scatter(np.cos(x), np.sin(x * 2), s=5, color='tab:red')
axs[1, 1].set_title('scatter')

fig.suptitle('Four charts in one figure')

fig.savefig('subplots.png')

We create a figure with two rows and two columns of charts.

fig, axs = plt.subplots(2, 2, figsize=(8, 6), layout='constrained')

For a grid, subplots returns a two-dimensional NumPy array of axes, indexed by row and column. The constrained layout places the charts so that their titles and labels do not overlap.

fig.suptitle('Four charts in one figure')

The suptitle method sets a title for the whole figure.

Subplots
Figure: Subplots

Styles

Matplotlib comes with predefined styles that change colours, fonts, grids, and backgrounds.

styles.py
import matplotlib.pyplot as plt

print(len(plt.style.available))
print(plt.style.available[:6])

x = [1, 2, 3, 4, 5]
y = [3, 5, 2, 6, 4]

with plt.style.context('ggplot'):

    fig, ax = plt.subplots()
    ax.plot(x, y, marker='o')
    ax.set_title('The ggplot style')
    fig.savefig('styles.png')

The plt.style.available list contains the names of the available styles. The plt.style.context context manager applies a style only to the charts created inside the with block; plt.style.use would change the style for the rest of the program. The chart uses the ggplot style, which imitates the look of the R ggplot2 library. The program prints the number of available styles and the first six names.

The ggplot style
Figure: The ggplot style
$ python styles.py
28
['Solarize_Light2', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight']

Annotations

Annotations and text help to explain the data in a chart.

annotate.py
import matplotlib.pyplot as plt

days = list(range(1, 15))
visits = [320, 340, 310, 360, 380, 220, 200, 400, 1250, 520, 430, 410, 230, 210]

fig, ax = plt.subplots(figsize=(7, 4.5))

ax.plot(days, visits, marker='o')

peak = visits.index(max(visits))
ax.annotate('Article on the front page', xy=(days[peak], visits[peak]),
            xytext=(10.5, 1100), arrowprops={'arrowstyle': '->'})

ax.axvspan(5.5, 7.5, alpha=0.2, color='gray')
ax.axvspan(12.5, 14, alpha=0.2, color='gray')
ax.text(6.5, 1150, 'weekend', ha='center')

ax.set_title('Daily visits')
ax.set_xlabel('Day')
ax.set_ylim(0, 1400)

fig.savefig('annotate.png')

The example shows daily visits of a website and explains the peak.

ax.annotate('Article on the front page', xy=(days[peak], visits[peak]),
            xytext=(10.5, 1100), arrowprops={'arrowstyle': '->'})

The annotate method writes the text at the xytext position and draws an arrow to the annotated point xy. Both positions are in data coordinates.

ax.axvspan(5.5, 7.5, alpha=0.2, color='gray')

The axvspan method shades a vertical band; we mark the weekends. The text method writes a plain text label.

Annotated line chart
Figure: Annotated line chart

Saving charts

The savefig method supports raster formats such as PNG and JPEG and vector formats such as SVG and PDF.

save_formats.py
from pathlib import Path
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(4, 3))
ax.plot([1, 2, 3], [2, 4, 3])
ax.set_title('Formats')

for name, opts in [('chart.png', {}), ('chart_hd.png', {'dpi': 300}),
                   ('chart.svg', {}), ('chart.pdf', {})]:
    fig.savefig(name, bbox_inches='tight', **opts)

for name in sorted(Path('.').glob('chart*')):
    print(f'{name}: {name.stat().st_size:,} bytes')

plt.close(fig)

We save one figure in four files. The dpi option sets the resolution of raster images; at 300 dpi, the PNG file has nine times more pixels than at the default 100 dpi. Vector formats scale without losing quality and are better for printing. The bbox_inches='tight' option crops the empty space around the chart. Finally, plt.close frees the figure; pyplot keeps references to all figures it created until they are closed.

$ python save_formats.py
chart.pdf: 7,518 bytes
chart.png: 15,073 bytes
chart.svg: 14,605 bytes
chart_hd.png: 50,882 bytes

Source

Matplotlib User Guide

Matplotlib examples gallery

In this article we have created charts in Python with Matplotlib. Each chart type is covered in more detail in the Matplotlib tutorials: line charts, scatter charts, bar charts, pie charts, subplots, and styles. See also Python pandas.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.