How can I use matplotlib.pyplot in a docker container?

I tried in my own way and it works fine.. #To run "matplotlib" inside docker, you must install these inside containers:-#
$yum install python3 -y //(must)
$yum install python3-tkinter -y //(must)
$pip3 install matplotlib // (must)
$pip3 install pandas (if required)
$pip3 install scikit-learn ( if required)

Now, run your container.

$docker run --rm -it --env=DISPLAY --workdir=/app -v="$PWD:/app <image_name> python3 model.py


Interestingly, I found quite nice and thorough solutions in ROS community. http://wiki.ros.org/docker/Tutorials/GUI

For my problem, my final choice is the second way in the tutorial:

docker run --rm -it \
   --user=$(id -u) \
   --env="DISPLAY" \
   --workdir=/app \
   --volume="$PWD":/app \
   --volume="/etc/group:/etc/group:ro" \
   --volume="/etc/passwd:/etc/passwd:ro" \
   --volume="/etc/shadow:/etc/shadow:ro" \
   --volume="/etc/sudoers.d:/etc/sudoers.d:ro" \
   --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \
   deepaul python test.python

As far as I know, there are two ways you can to this:

  1. You can give Jupyter a try. Install Jupyter via Conda or pip, and then run Jupyter-notebook server. By exporting the server port of Jupyter, you can visit the Jupyter-notebook via a browser. You can then create a new python notebook and import the .py file you have, copy the code under your if __name__ == '__main__' to the new notebook if necessary. Finally, run the code in Jupyter, the image will show up below the code on the web page. matplotlib works smoothly with Jupyter. If you are willing to open a browser to run the code and view the result, this is the best way I can think of.
  2. You can use the matplotlib headlessly. That means to remove all the code such as plt.show(). Use plt.savefig to save figures to filesystem instead of showing it in an opened window. Then you can check out these saved images using any image viewer.

I tried mounting X11 to docker images some time ago, like YW P Kwon's answer. It will only work on systems that use X11, and you can do this only on a local machine (I am not sure if X11 forward works). It is also not recommended in docker. While with the Jupyter and Headless solution, you can run your code on any platform. But you do need to modify your code a little bit.