2

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

OhMad
  • 6,871
  • 20
  • 56
  • 85

1 Answers1

4

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.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • I get a 'main thread not in main loop' exception every once in a while, do you know what that is or if it's related to this approach? – OhMad Sep 17 '17 at 15:08
  • No, I have no idea where that comes from. It should not depend on this code here, and "once in a while" really does not sound like a problem with the code itself. – ImportanceOfBeingErnest Sep 17 '17 at 15:10
  • I am trying to import matplotlib to run this code in my app like this `import matplotlib.pyplot as plt, mpld3` but it says `ModuleNotFoundError: No module named 'mpld3'`, How do I solve this ? I already have matplotlib installed – Rahul Sharma Jun 03 '19 at 05:42
  • @Rahul If you want to use `mpld3` you need to install it. – ImportanceOfBeingErnest Jun 03 '19 at 10:21
  • @ImportanceOfBeingErnest I did that and it works like a charm but could you help me with one other thing ? – Rahul Sharma Jun 03 '19 at 10:26