Django使用mpld3在HTML中渲染Matplotlib图表 [英] Django Rendering Matplotlib chart in HTML using mpld3

查看:627
本文介绍了Django使用mpld3在HTML中渲染Matplotlib图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Django和MPLD3 / Matplotlib将 mpld3图表添加到我的webapp中。如此处所述,获取图的HTML代码应该很简单用python编写。

I'm trying to get a mpld3 chart into my webapp using Django and MPLD3/Matplotlib. As described here it should be straightforward getting the HTML code of the figure written in python.

Views.py

def figure(request):

    np.random.seed(9615)

    N = 100
    df = pd.DataFrame((.1 * (np.random.random((N, 5)) - .5)).cumsum(0),
                  columns=['a', 'b', 'c', 'd', 'e'], )

    # plot line + confidence interval
    fig, ax = plt.subplots()
    ax.grid(True, alpha=0.3)

    for key, val in df.iteritems():
        l, = ax.plot(val.index, val.values, label=key)
        ax.fill_between(val.index,
                        val.values * .5, val.values * 1.5,
                        color=l.get_color(), alpha=.4)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_title('Interactive legend', size=20)

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

    return render(request, "dashboard.html", {'active_page' : 'dashboard.html', 'div_figure' : html_fig})

dashboard.html

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

AFAIK,python代码被翻译成javascript,应该在views.py呈现仪表板时执行。 html,对吗?

AFAIK, the python code gets translated into javascript and should be executed when views.py is rendering dashboard.html, right?

结果,我得到的HTML代码在我的dashboard.hmtl上显示为文本。

As result, I get the HTML code displayed as text on my dashboard.hmtl.

问题:如何显示图表?我是否需要解析方法html_to_fig返回的HTML字符串?

QUESTION: How do I get the chart displayed? Do I need to parse the HTML string which is returned by the method html_to_fig?

推荐答案

在html中尝试这个

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

这篇关于Django使用mpld3在HTML中渲染Matplotlib图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆