Matplotlib - Mpld3 fig_to_html() in Django

5.3k Views Asked by At

I am trying to dispaly a scatter of points in mpld3 in my browser.

This is my views.py snippet:

plt.scatter([1, 10], [5, 9])
fig = plt.figure()
html_graph = mpld3.fig_to_html(fig)

return render(request, 'home.html', {'graph': [html_graph]})

And inside of home.html:

{% for elem in graph %}
   {{elem|safe}}
{% endfor %}

But the only thing I see are the controls. I also tried it with:

fig, ax = plt.subplot()

But this only displays the controls along with the graph, without the scattered points.

Any suggestions?

Thanks in Advance

1

There are 1 best solutions below

5
On BEST ANSWER

You need to first create the figure, then plot the scatter to it.

fig = plt.figure()
plt.scatter([1, 10], [5, 9])
html_graph = mpld3.fig_to_html(fig)

or, maybe better

fig, ax = plt.subplots()
ax.scatter([1, 10], [5, 9])
html_graph = mpld3.fig_to_html(fig)

because in the latter case you are sure to plot the scatter to the axes ax that is part of the figure you are showing.