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

1 Answer 1

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.

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

5 Comments

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?
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.
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 If you want to use mpld3 you need to install it.
@ImportanceOfBeingErnest I did that and it works like a charm but could you help me with one other thing ?

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.