WSL | Show a Graph using Python matplotlib

Using python matplotlib package, you can draw various graphs.
This article introduces how to use matplotlib in WSL Ubuntu.




  • Windows 11
  • WSL Ubuntu 22.04
  • Python 3.10.6


Updating and Installing Packages

Updating Ubuntu Packages

$ sudo apt update
$ sudo apt upgrade

Installing python3-pip

$ sudo apt install python3-pip

Installing matplotlib

$ pip install matplotlib

Drawing a Graph by matplotlib

Sample Code

Here is sample code that draw a graph for sin(x) in the range [-5.0, 5.0].

import math
import matplotlib.pyplot

xs = [0.1 * i - 5 for i in range(100)]
ys = [math.sin(x) for x in xs]

matplotlib.pyplot.plot(xs, ys)

Dealing with Errors

If you have not installed the backend for GUI, the runtime will show following error.

$ python3
/ANY_PATH/ UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.

One of solutions is to install tkinter to Ubuntu.

$ sudo apt install python3-tk


Run it again and you will get the graph of sin(x).

Let's share this post !


To comment