2

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 Answers1

1

try this in the html

<div id="fig_container">
   {{ div_figure|safe }}
</div>
Exprator
  • 26,992
  • 6
  • 47
  • 59
  • Thank you! Everything works fine. Could you please explain `|safe` exztension? Thx. – S0urc3_C0d3 Jul 05 '17 at 23:13
  • or a reference? tHx – S0urc3_C0d3 Jul 05 '17 at 23:37
  • you can look for django template filters for reference, by d way safe is for rendering html from the content that you are passing. its a filter basically which tells django that the html in the content is safe to render as html – Exprator Jul 06 '17 at 03:37