Install matplotlib
In A Docker Container
We’re Earthly. We make building software simpler and therefore faster using containerization. It’s an ideal tool for dealing with your python container builds. Check it out.
matplotlib
is an excellent library for creating graphs and visualizations in Python. For example, I used it to generate the performance graphs in my merging article, and internally, we use it now and again for visualizing any metrics we produce. It is a bit hard to install inside a docker container, though.
Installing Matplotlib in Alpine Linux
On Alpine, or an Alpine-based docker image, it’s possible to install matplotlib
; however it will involve compiling it from source as pip does not provide any pre-compiled binaries – this will take quite a bit of time. If you don’t mind compiling from source, you will need to have its dependencies in place to make this work:
FROM python:3.6-alpine
RUN apk add g++ jpeg-dev zlib-dev libjpeg make
RUN pip3 install matplotlib
Installing Matplotlib in Ubuntu
On Ubuntu, or a Ubuntu-based docker image, the process is much simpler:
FROM ubuntu:20.10
RUN apt-get update && apt-get install -y python3 python3-pip
RUN pip3 install matplotlib
In either case, after you’ve installed it, you can quickly generate great graphs and visualizations:
import numpy as np
from scipy.interpolate import splprep, splev
import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch
= 400
N = np.linspace(0, 3 * np.pi, N)
t = 0.5 + np.cos(t)
r = r * np.cos(t), r * np.sin(t)
x, y = plt.subplots()
fig, ax
ax.plot(x, y)"X value")
plt.xlabel("Y value")
plt.ylabel('1.png') plt.savefig(
Appendix: Alpine vs Ubuntu Pip Install
Why is the Ubuntu process fast and simple and the Alpine process slow? The reason is glibc
. The pip wheels for matplotlib
are compiled c/c++ programs that dynamically link to glibc
and Alpine does not have glibc
.
Alpine tries to stay small and so uses musl-libc
instead. Unfortunately, this means compiling from source on Alpine, which can be a lengthy process.
ThisGuyCantEven on Stack Overflow has more details:
Pip looks first for a wheel with the correct binaries, if it can’t find one, it tries to compile the binaries from the c/c++ source and links them against
musl
. In many cases, this won’t even work unless you have the python headers from python3-dev or build tools like make.Now the silver lining, as others have mentioned, there are
apk
packages with the proper binaries provided by the community, using these will save you the (sometimes lengthy) process of building the binaries.