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 Answer 1

1

try this in the html

<div id="fig_container">
   {{ div_figure|safe }}
</div>
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Everything works fine. Could you please explain |safe exztension? Thx.
or a reference? tHx
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

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.