How to place a matplotlib plot into an html container using mpld3 and flask
After working for a while, I have found a solution that seems to work and achieve the behavior I want. Note that I am using the twitter bootstrap css and javascript packages.
Basically, I make a button group:
<div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary"> <input type="radio" name="options" id="home"> Option 1 </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option2"> Option 2 </label> <label class="btn btn-primary"> <input type="radio" name="options" id="option3"> Option 3 </label>
Then in the javascript from the mpld3-flask example I use:
$('.btn-primary').on('click', function(){ var qu = {"plot_type":$(this).find('input').attr('id')} $(this).addClass('active').siblings().removeClass('active'); $.ajax({ type: "POST", async:true, contentType: "application/json; charset=utf-8", url: "/query", data: JSON.stringify(qu), success: function (data) { var graph = $("#container"); graph.html(data); $("#container").show(); }, dataType: "html" }); });
Now I have a radio-button bar, with the currently active plot button set to 'active', which only requires one click on one of the buttons to draw a new plot.
EDIT: After learning more about flask and Jinja2, it is also easy to pass the mpld3-generated html to a a template, but there is a slight gotcha; it looks something like this
In the return of your python routing function:
return render_template('index.html', plot=mpld3_html)
Then in the html template you can reference this html with
{{plot|safe}}
Hope this helps someone else.