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.

Languages

TOC

Environment

  • Windows 11
  • WSL Ubuntu 22.04
  • Python 3.10.6

Preparation

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)
matplotlib.pyplot.show()

Dealing with Errors

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

$ python3 main.py
/ANY_PATH/main.py:8: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
  matplotlib.pyplot.show()

One of solutions is to install tkinter to Ubuntu.

$ sudo apt install python3-tk

Output

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

Let's share this post !

Comments

To comment


The reCAPTCHA verification period has expired. Please reload the page.

TOC