Open In App

Create Scatter Charts in Matplotlib using Flask

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to create charts in Matplotlib with Flask. We will discuss two different ways how we can create Matplotlib charts in Flask and present it on an HTML webpage with or without saving the plot using Python.

File structure

Create Charts in Matplotlib with flask

 

Create and Save the Plot in the Static Directory

Here, We first created a get_plot() function which generates the Matplotlib plot and returns the plot object. Python’s Numpy library generates random data for this plot. It is not necessary to import if you are defining your own data. The root URL (‘/’) first calls this function to get the plot object. It then saves this plot object as ‘plot.png’ under the images folder present inside the static directory. This is the default location defined by Flask for static files like images, CSS, JS, etc.  The final step is to render the below HTML script which reads the image file from the directory and renders it to the web browser as shown in the output image.

Python3




# Importing required functions 
import numpy as np
import matplotlib.pyplot as plt
from flask import Flask, render_template
  
  
# Flask constructor 
app = Flask(__name__)
  
# Generate a scatter plot and returns the figure
def get_plot():
    data = {
        'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)
    }
    data['b'] = data['a'] + 10 * np.random.randn(50)
    data['d'] = np.abs(data['d']) * 100
  
    plt.scatter('a', 'b', c='c', s='d', data=data)
    plt.xlabel('X label')
    plt.ylabel('Y label')
    return plt
  
# Root URL
@app.get('/')
def single_converter():
    # Get the matplotlib plot 
    plot = get_plot()
  
    # Save the figure in the static directory 
    plot.savefig(os.path.join('static', 'images', 'plot.png'))
  
    return render_template('matplotlib-plot1.html')
  
# Main Driver Function 
if __name__ == '__main__':
    # Run the application on the local development server 
    app.run(debug=True)


Save the HTML file as ‘matplotlib-plot1.html’ under the templates folder in the root directory.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>Matplotlib Plot</title>
</head>
  
<body>
    <h1>How to Create Charts in Matplotlib with flask - Example 1</h1>
    <img src="{{ url_for('static', filename='images/plot.png') }}">
</body>
  
</html>


Output:

Create Charts in Matplotlib with flask

Example 1 – Output

Generating a Base64 I/O String of the Plot

We will generate the base64 I/O) string format for the image and pass this to the template to render the plot. Here, We first created a get_plot() function which generates the Matplotlib plot and returns the plot object. Python’s Numpy library generates random data for this plot. It is not necessary to import if you are defining your own data. The root URL (‘/’) first calls this function to get the plot object. It then creates a Base64 I/O equivalent format of the string using python’s built-in ‘io’ and ‘base64’ modules. The final step is to render the below HTML script and also pass this string to the template. The template reads the image file using the string that is passed to it.

Python




# Importing required functions
from flask import Flask, render_template
import matplotlib.pyplot as plt
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
  
  
# Flask constructor
app = Flask(__name__)
  
# Generate a scatter plot and returns the figure
def get_plot():
  
    data = {
        'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)
    }
  
    data['b'] = data['a'] + 10 * np.random.randn(50)
    data['d'] = np.abs(data['d']) * 100
  
    plt.scatter('a', 'b', c='c', s='d', data=data)
    plt.xlabel('X label')
    plt.ylabel('Y label')
  
    return plt
  
# Root URL
@app.get('/')
def single_converter():
    # Get the matplotlib plot
    plot = get_plot()
  
    # Save the figure in the static directory
    plot.savefig(os.path.join('static', 'images', 'plot.png'))
  
    # Close the figure to avoid overwriting
    plot.close()
    return render_template('matplotlib-plot1.html')
  
# Main Driver Function
if __name__ == '__main__':
    # Run the application on the local development server
    app.run(debug=True)


Save the HTML file as ‘matplotlib-plot2.html’ under the templates folder in the root directory.

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>Matplotlib Plot</title>
</head>
  
<body>
    <h1>How to Create Charts in Matplotlib with flask - Example 2</h1>
    <img src="data:image/png;base64,{{ s }}">
</body>
  
</html>


Output:

Create Charts in Matplotlib with flask

Example 2 – Output

Related Articles: How to Add Graphs to Flask apps



Last Updated : 05 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads