如何使用mpld3和flask将matplotlib图放入html容器中

7 投票
1 回答
4595 浏览
提问于 2025-04-20 12:07

我正在尝试使用mpld3-flask的示例(https://github.com/nipunreddevil/mpld3-flask)作为模板,想实现一些特定的功能。我希望在头部导航栏上添加链接,直接跳转到不同的图表,而不是使用单选按钮的查询表单。

目前,上面的示例代码在templates/index.html中创建了一个容器,当用户点击“查看图表”按钮提交查询时,会在这个容器中填充一个图表。根据我所理解的,这段代码在index.html中:

$("#query").click(function() {  

  $("#loading-div-background").show();
  $("#container").hide();
  var plot_type = $('input:radio[name=plot_type]:checked').val();
  var qu = {"plot_type":plot_type}
  $.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);   
     $("#loading-div-background").hide();      
     $("#container").show();
   },
   dataType: "html"
 });
});

我想要的其实是把现在的头部导航栏(上面有“首页”)改成可以显示不同的图表,每个图表在不同的页面上。我希望能通过不同的链接跳转,然后用图表的数据填充模板的html代码,而不需要用户进行查询。

我对html还是有点陌生,现在对JavaScript几乎一无所知。我觉得用flask和jinja2应该有比较简单的方法来实现这个功能,但我一直没能搞明白。

我在处理这些语言结合时产生的一些不清晰的命名空间时遇到了一些麻烦。我在自己的Python编程中通常对命名空间非常严格(也就是说,我从来不使用'from ____ import *'),所以这让我有点抓狂。

1 个回答

7

经过一段时间的工作,我找到了一种看起来有效的解决方案,能够实现我想要的效果。需要注意的是,我使用的是Twitter Bootstrap的CSS和JavaScript包。

基本上,我创建了一个按钮组:

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

然后在mpld3-flask示例的JavaScript中,我使用了:

$('.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"
  });  
}); 

现在我有了一个单选按钮条,当前激活的绘图按钮被设置为'active',只需点击其中一个按钮,就可以绘制新的图表。

编辑:在学习了更多关于Flask和Jinja2的知识后,我发现将mpld3生成的HTML传递给模板也很简单,但有一点小注意;它看起来像这样:

在你的Python路由函数的返回中:

return render_template('index.html', plot=mpld3_html)

然后在HTML模板中,你可以用以下方式引用这个HTML:

{{plot|safe}}

希望这能帮助到其他人。

撰写回答