So, bear with me as I\'m VERY new to Django, Python, and web-development in general. What I want to do is display a graph that I\'ve made using matplotlib. I had it working to w
I know this question is tagged as matplotlib, but I needed to do the same thing and I have found plotly to be easier to use and visually appealing as well. You can simply plot a graph and then in the view get the html code of the graph as :
# fig is plotly figure object and graph_div the html code for displaying the graph
graph_div = plotly.offline.plot(fig, auto_open = False, output_type="div")
# pass the div to the template
In the template do:
<div style="width:1000;height:100">
{{ graph_div|safe }}
</div>
I think you should uncoment this line:
#canvas.print_png(response)
You can easily return plot using django HttpResponse instead using some extra libs. In the matplotlib there is a FigureCanvasAgg which gives you access to canvas where plot is rendered. Finaly you can simple return it as HttpResonse. Here you have very basic example.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_agg import FigureCanvasAgg
from django.http import HttpResponse
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()
response = HttpResponse(content_type = 'image/png')
canvas = FigureCanvasAgg(fig)
canvas.print_png(response)
return response
I searched quite a bit until I found a solution that worked for me when it comes to rendering a matplotlib image on a Django page. Often, simply a lengthy string was printed instead of a visualization being produced. So, what finally worked for me was the following:
First, the imports:
import matplotlib.pyplot as plt
from io import StringIO
import numpy as np
The dummy function returning a graphic is the following:
def return_graph():
x = np.arange(0,np.pi*3,.1)
y = np.sin(x)
fig = plt.figure()
plt.plot(x,y)
imgdata = StringIO()
fig.savefig(imgdata, format='svg')
imgdata.seek(0)
data = imgdata.getvalue()
return data
This one can be called by some other function using and rendering the image returned by return_graph()
:
def home(request):
context['graph'] = return_graph()
return render(request, 'x/dashboard.html', context)
And in the dashboard.html
file, the graphic is embedded by the following command:
{{ graph|safe }}
If you want to embed matplotlib figures to django-admin you can try django-matplotlib field. This field doesn't create a column in the database, but is rendered as a regular field. You don't need to customize/subclass admin.ModelAdmin
, just use this field in your models and define how the figure will be generated.