Django Rendering Matplotlib chart in HTML using mpld3

☆樱花仙子☆ 提交于 2019-12-08 08:12:49

问题


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, the python code gets translated into javascript and should be executed when views.py is rendering dashboard.html, right?

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

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?


回答1:


try this in the html

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


来源:https://stackoverflow.com/questions/44924890/django-rendering-matplotlib-chart-in-html-using-mpld3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!