2

I'm trying to write a Django web app which displays a plot of a function with several parameters, however I wasn't able to find any examples of this on the web.

So far I've created an mpl app within a mpldjango project with the following structure:

.
├── db.sqlite3
├── manage.py
├── mpl
│   ├── __init__.py
│   ├── __pycache__
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
└── mpldjango
    ├── __init__.py
    ├── __pycache__
    ├── settings.py
    ├── urls.py
    └── wsgi.py

where mpl/views.py is

import django
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np

def make_canvas(rate):
    rate = float(rate)
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.add_subplot(111)
    x = np.arange(-2, 1.5, 0.01)
    y = np.sin(np.exp(rate * x))
    ax.plot(x,y)
    return canvas

def mplimage(request, rate=2):
    canvas = make_canvas(rate=rate)
    response=django.http.HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response

and mpldjango/urls.py is

from django.conf.urls import include, url
from django.contrib import admin
import mpl.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'mplimage.png/a=(?P<rate>[0-9]+)', mpl.views.mplimage),
    url(r'mplimage.png', mpl.views.mplimage),
]

Now, after python manage.py runserver, if I browse to http://localhost:8000/mplimage.png/a=3, for example, I get the plot with the rate parameter set to 3:

enter image description here

and similar if I set a=2 in the URL.

This is not the interface I want however: I would prefer to fill out a form containing plot parameters and have the plot update when I submit it. It seems to me that this would be a very standard code example, but I wasn't able to find any. How would I go about this?

1 Answer 1

4

What I do is that I generate a matplotlib figure, save it as a png to Django /media folder configured in your settings.py https://docs.djangoproject.com/en/1.11/ref/settings/#media-root and then link it to a page you return instead of the image.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.