Python Plotting API: Expose your scientific python plots through a flask API

Python Plotting API: Expose your scientific python plots through a flask APIAlexander MuellerBlockedUnblockFollowFollowingDec 23In my daily work as a data scientist, I often have the need to integrate relatively complex plots into back-office applications..These plots are mainly used to illustrate algorithmic decisions and give data intuitions to operational departments.A possible approach here would be to build an API that returns data and let the front-end of the application render the data with a more or less complex javascript charting library..Every time I would now like to change something I would need to change both front-end and backend.Consequently, I looked for a fast, easy and maintainable solution to make plots available in any web front-end application..I also looked for a solution that allowed me to change my plots in one place with the need of always changing a frontend when e.g..some new feature request came in.What I came up with is simply to build the plots in python with matplotlib, seaborn, etc and then expose them through flask to the web..Sound easy?.It is easy!.I will walk you through step by step..Maybe it will help you as much as me.What components do we need:A dataset: We will use the breast cancer dataset from scikit-learnA plot: Let us take a simple correlation plot from seaborn for startersAn API: Here we will create simple API with the use of flaskSo let us first load the data and do a plot:Plotting a plot and return it as BytesIOA correlation matrix plotThis will result in the plot left..As you can see the trick here is to save the plot into a BytesIO object..We can now expose this BytesIO object through a flask API and we’re done!A simple endpoint to return the plotIn the snippet above we create a very simple endpoint, that should return a plot image when a client is requesting it via the given route..So if your server runs on localhost the image will be available under http://localhost:5000/plots/breast_cancer_data/correlation_matrix.With flask you can use the send_file function that helps you to send a file to the requesting client.. More details

Leave a Reply