[PYTHON] Display matplotlib diagrams in a web application

Right now, I think that the JavaScript library will probably make cool graphs, but no, I'm not sure, but I still want to use the familiar matplotlib in web applications.

However, since matplotlib draws using X11, if you think that it may be difficult to use in a web application, that is not the case.

Create image data using AGG (Anti-Grain Geometry) for the back end.

things to do

Draw a graph created with matplotlib in a flask web application. The reason for using flask is because it is convenient, so I think that you can do the same if you do the same without using it.

Also, do the following two patterns.

Return png data in response

Make a chart

For the time being, I need a chart to display something, so

I will make a graph.

These numbers don't seem to have a deep meaning, but they don't. The title of the graph should be "IMINASHI GRAPH".

fig, ax = matplotlib.pyplot.subplots()
ax.set_title(u'IMINASHI GRAPH')
x_ax = range(1, 284)
y_ax = [x * random.randint(436, 875) for x in x_ax]
ax.plot(x_ax, y_ax)

Like this.

iminashi_graph.png

Display in web app

The processing flow is like this.

  1. Create png data for charts
  2. Write the data to the buffer of cStringIO.StringIO
  3. Return data as image content in response

Maybe it's faster to look at the code.

@app.route('/graph1')
def graph1():
    import matplotlib.pyplot
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    import cStringIO
    import random

    fig, ax = matplotlib.pyplot.subplots()
    ax.set_title(u'IMINASHI GRAPH')
    x_ax = range(1, 284)
    y_ax = [x * random.randint(436, 875) for x in x_ax]
    ax.plot(x_ax, y_ax)

    canvas = FigureCanvasAgg(fig)
    buf = cStringIO.StringIO()
    canvas.print_png(buf)
    data = buf.getvalue()

    response = make_response(data)
    response.headers['Content-Type'] = 'image/png'
    response.headers['Content-Length'] = len(data)
    return response

Now, if you access it from a web browser, you will see the image.

iminashi_graph_on_brw.png

Create an image file as a temporary file

Another one is this one.

The process is like this.

  1. Export the chart as a png file
  2. Return png file in response
  3. Delete the png file

The interesting one would be 3. Considering simultaneous access from multiple people, I think it is better to use a random character string for the file name. However, in that case, the number of files will increase steadily, so you have to delete them properly after displaying the files.

Use the same graph as before. The title of the graph should be "IMINASHI GRAPH 2".

@app.route('/graph2')
def graph2():
    import matplotlib.pyplot
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    import random
    import string
    import os

    class TempImage(object):

        def __init__(self, file_name):
            self.file_name = file_name

        def create_png(self):
            fig, ax = matplotlib.pyplot.subplots()
            ax.set_title(u'IMINASHI GRAPH 2')
            x_ax = range(1, 284)
            y_ax = [x * random.randint(436, 875) for x in x_ax]
            ax.plot(x_ax, y_ax)

            canvas = FigureCanvasAgg(fig)
            canvas.print_figure(self.file_name)

        def __enter__(self):
            return self

        def __exit__(self, exc_type, exc_value, traceback):
            os.remove(self.file_name)

    chars = string.digits + string.letters
    img_name = ''.join(random.choice(chars) for i in xrange(64)) + '.png'

    with TempImage(img_name) as img:
        img.create_png()
        return send_file(img_name, mimetype='image/png')

There are several possible ways to delete it after returning a response, but in this example we use the context manager to destroy it. This is the most Python-like image.

iminashi_graph_on_brw_2.png

It was displayed. It may be easier to use if it is made into a file.

Recommended Posts

Display matplotlib diagrams in a web application
Steps to develop a web application in Python
[Django3] Display a web page in Django3 + WSL + Python virtual environment
Creating a web application using Flask ②
Web application development memo in python
Creating a voice transcription web application
Build a web application with Django
Creating a web application using Flask ①
Creating a web application using Flask ③
Creating a web application using Flask ④
How to suppress display error in matplotlib
Display a list of alphabets in Python 3
External display of matplotlib diagrams using tkinter
Display Matplotlib xy graph in PySimple GUI.
[Python] A quick web application with Bottle!
Display pyopengl in a browser (python + eel)
Run a Python web application with Docker
Web application development in Go language_Hands-on day 1
I tried benchmarking a web application framework
Create a web service in Flask-SQLAlchemy + PostgreSQL
I made a WEB application with Django
I made a web application in Python that converts Markdown to HTML
What I was addicted to when creating a web application in a windows environment
[Python] How to draw a histogram in Matplotlib
Create a web server in Go language (net/http) (2)
Heppoko develops web service in a week # 2 Domain search
This is a sample of function application in dataframe.
(Python) Try to develop a web application using Django
Launch a Python web application with Nginx + Gunicorn with Docker
How to display DataFrame as a table in Markdown
Convenient to use matplotlib subplots in a for statement
Create a web server in Go language (net / http) (1)
Display a histogram of image brightness values in python
install diagrams in wsl
How to display the regional mesh of the official statistics window (eStat) in a web browser
A memorandum about matplotlib
View images in Matplotlib
dict in dict Makes a dict a dict
2D plot in matplotlib
Web application using Bottle (1)
Create a web application that recognizes numbers with a neural network
Display "Hello World" created in the local environment on the web
Application to display and search local memos (diary) in Python
Get a Python web page, character encode it, and display it
Display Google Maps on a web page (Spring Boot + Thymeleaf)
Display a web page with FastAPI + uvicorn + Nginx (SSL / HTTPS)
A story about everything from data collection to AI development and Web application release in Python (3. AI development)