Saturday, 28 December 2019
django matplotlib response as png
#matplot/views
from django.http import HttpResponse
import matplotlib.pyplot as plt
import numpy as np
import io
def index(request):
return HttpResponse('<h1>matplotlib app homepage</h1>')
def plot(request):
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
buf = io.BytesIO()
plt.savefig(buf, format='png')
plt.close(fig)
response = HttpResponse(buf.getvalue(), content_type='image/png')
return response
--------------------------------
#matplot/urls
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('chart/', views.plot, name='chart')
]
------------------------------
#django_matplotlib/urls
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('matplot/', include('matplot.urls')),
]
reference:
https://stackoverflow.com/questions/49542459/error-in-django-when-using-matplotlib-examples
https://stackoverflow.com/questions/40534715/how-to-embed-matplotlib-graph-in-django-webpage
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment