3
    plt.figure(figsize=(8, 8))

    sns.heatmap(conf_matrix, annot=True, fmt="d");
    plt.title("Confusion matrix")
    plt.ylabel('True class')
    plt.xlabel('Predicted class')

    html_fig = mpld3.fig_to_html(plt,template_type='general')
    plt.close(plt)

Code in HTML file to fetch the image :

    <div id="fig_container">
    {{ div_figure|safe }}
</div>

Using latest versions of Python and Django. On executing the attribute error is displayed

module 'matplotlib.pyplot' has no attribute 'canvas'

I am new to it and unable to resolve the error. Please help!!!

2
  • 1
    Please add a few lines more context around that code snippet, particularly your import of pyplot and your use of canvas. Commented Mar 18, 2019 at 8:07
  • It seems you call mpld3.fig_to_html(matplotlib.pyplot) which is not correct. That function would probably expect a figure as input, fig = plt.figure(); ....; mpld3.fig_to_html(fig) Commented Mar 18, 2019 at 11:03

1 Answer 1

3

I had a similar issue. You probably have solved the problem by now, but anyway I'm posting an answer.

The main point here is that mpld3 works with the fig object used in matplotlib. Like this:

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4])
html_fig = mpld3.fig_to_html(fig)

So for your solution you should get the figure object from your seaborn plot. It can be done either this way (whatch the ax argument):

fig, ax = plt.subplots()
sns.heatmap(conf_matrix, annot=True, fmt="d", ax=ax)
html_fig = mpld3.fig_to_html(fig)

Or this way:

fig = sns.heatmap(conf_matrix, annot=True, fmt="d").get_figure()
html_fig = mpld3.fig_to_html(fig)

If you want to include seaborn plots and matplotlib in general in django projects using mpld3 I'd recommend to view this question

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

Comments

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.