【问题标题】:Getting attribute error : module 'matplotlib.pyplot' has no attribute 'canvas'获取属性错误:模块“matplotlib.pyplot”没有属性“画布”
【发布时间】:2019-08-08 13:19:28
【问题描述】:
    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)

HTML 文件中用于获取图像的代码:

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

使用最新版本的Python 和Django。执行时显示属性错误

模块'matplotlib.pyplot'没有属性'canvas'

我是新手,无法解决错误。请帮忙!!!

【问题讨论】:

  • 请在代码 sn-p 周围添加几行上下文,特别是您对 pyplot 的导入和对 canvas 的使用。
  • 您似乎调用了mpld3.fig_to_html(matplotlib.pyplot),这是不正确的。该函数可能需要一个数字作为输入,fig = plt.figure(); ....; mpld3.fig_to_html(fig)

标签: django python-3.x matplotlib django-templates attributeerror


【解决方案1】:

我遇到了类似的问题。您现在可能已经解决了问题,但无论如何我都会发布答案。

这里的重点是 mpld3 与 matplotlib 中使用的 fig 对象一起工作。像这样:

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

因此,对于您的解决方案,您应该从 seaborn 图中获取图形对象。可以通过这种方式完成(whatch theax 参数):

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

或者这样:

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

如果你想在使用 mpld3 的 django 项目中包含 seaborn 绘图和 matplotlib,我建议查看 this question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 2021-07-17
    • 2021-09-25
    • 2018-01-21
    相关资源
    最近更新 更多