Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deploy 'matplotlib', the Python library, as a Lambda Layer in AWS?

I have tried zipping and structuring the zip in the python/lib/python3.7/site-packages/{matplotlib here} But it says couldn't import ft2font which is in matplotlib/init_.py

Interestingly there is no other files with that name in my package. I tried pip install and pip3 install on different OS but yet no luck

like image 543
Makalp Patel Avatar asked Feb 16 '26 04:02

Makalp Patel


1 Answers

I have created a matplotlib layer for AWS lambda using docker following these steps:

sudo docker pull amazonlinux
sudo docker run -it amazonlinux:latest /bin/bash

# inside container
yum -y install python37 zip
python3 -m venv python
source python/bin/activate
pip3 install matplotlib
deactivate 
rm -rf python/{bin,include,lib64,pyvenv.cfg} python/lib/python3.7/site-packages/{__pycache__,easy_install.py,numpy*,pip*,pkg_resources,setuptools*}
zip -r aws_lambda_python37_layer_matplotlib.zip python/

# in other terminal, copy file from container to host
CONTAINER_ID=$(sudo docker ps|grep amazonlinux|cut -d " " -f1)
sudo docker cp ${CONTAINER_ID}:/aws_lambda_python37_layer_matplotlib.zip .

# exit container
exit

Note that this script deletes numpy from the layer which is necessary due to size restrictions of a single lambda layer. So you will need to enable the official numpy/scipy layer from AWS in your lambda function as well.

You can also do this without docker on a small EC2 instance. You can find the resulting zip here: https://github.com/ttor/aws_lambda_python37_layer_matplotlib

like image 109
T.D. Avatar answered Feb 18 '26 18:02

T.D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!