Matplotlib Get Started

Install Matplotlib, confirm it works, and draw your very first figure.

Installing Matplotlib

Matplotlib is distributed through the Python Package Index (PyPI), so the standard way to install it is with pip, the package manager that ships with Python. Open a terminal and run pip install matplotlib. If you have both Python 2 and Python 3 on your system, or multiple Python versions, use python -m pip install matplotlib to guarantee the package is installed for the interpreter you intend to use.

If you use Anaconda or Miniconda for data science work, Matplotlib usually comes preinstalled, or you can add it with conda install matplotlib. Either approach gives you the same library once it is on your system.

Confirming the installation

Once installed, you can check that everything is working from inside Python itself. Import matplotlib and read its __version__ attribute, which prints the version number that was installed.

Example

import matplotlib

print(matplotlib.__version__)

Drawing your first figure

Matplotlib's most commonly used entry point is the pyplot module, conventionally imported as plt. Pass a list of numbers to plt.plot() to draw a line chart, then call plt.show() to open a window (or render inline, in a notebook) displaying the figure.

Example

import matplotlib.pyplot as plt

values = [1, 4, 9, 16, 25]

plt.plot(values)
plt.show()

Where to write your code

  • A plain .py script run from the terminal, where plt.show() opens a pop-up window
  • A Jupyter Notebook or JupyterLab, where figures render directly below the cell
  • An IDE such as VS Code or PyCharm with a Python or Jupyter extension installed
  • An online notebook service, when you do not want to install anything locally
Note: In a plain script, nothing appears on screen until you call plt.show(). Forgetting that line is the most common reason a Matplotlib script seems to "do nothing".

Exercise: Matplotlib Get Started

Which command installs Matplotlib using pip?