반응형

[python] mpld3를 이용해서 python의 그림을 웹에 올려보자.https://frhyme.github.io/python-libs/plt_mpld3/#matplotlibpyplot%EB%A1%9C-%EA%B7%B8%EB%A6%B0-%EA%B7%B8%EB%A6%BC%EC%9D%84-%ED%8E%B8%ED%95%98%EA%B2%8C-html%EB%A1%9C-%EB%B0%94%EA%BE%B8%EC%9E%90

 

mpld3를 이용해서 python의 그림을 웹에 올려보자.

matplotlib.pyplot로 그린 그림을 편하게 html로 바꾸자.

frhyme.github.io

 

matplotlib.pyplot로 그린 그림을 편하게 html로 바꾸자.Permalink

  • 파이썬으로 코딩하는 사람들은 시각화할때 대부분 matplotlib를 사용할 것이라고 생각합니다. 특히 matplotlib는 jupyter notebook과 붙으면 매우 굉-장해집니다. 그림을 바로 그리고 고치고, 다시 그리고 괜찮으면 저장, 하는 등의 작업을 수행하게 되죠.
  • 아무튼, 그냥 개인이 저장해서 처리한다면 아무 문제가 없지만, 이걸 웹에 뿌려주고 싶을 때는 이게 생각처럼 되지 않습니다. 그냥 그림으로 만들어서 전달해도 되지만, 그럴 경우에는 화면의 비율등에 따라서 깨질 수 있고, 이는 글자크기, 간격 등에 모두 영향을 미치게 되니까 아주 엉망인 그림이 만들어질 가능성이 높습니다.
    • 물론 svg파일로 만들어서 전달하는 것도 방법입니다만, 이 경우에도 어느 정도의 문제가 발생할 수는 있습니다.
  • 가장 좋은 선택지는, 웹상의 요소로 변환하는 것이 될것이고, 그 방법중 하나로 mpld3와 같은 라이브러리를 사용해서 처리할 수 있습니다.

what is mpld3?Permalink

The mpld3 project brings together Matplotlib, the popular Python-based graphing library, and D3js, the popular JavaScript library for creating interactive data visualizations for the web. The result is a simple API for exporting your matplotlib graphics to HTML code which can be used within the browser, within standard web pages, blogs, or tools such as the IPython notebook.

  • 공식 홈페이지에서 가져왔습니다. 간단히 정리하면, mpld3는 매트플롯립과 d3js를 사용해서 웹의 인터랙티브 데이터 시각화 를 가능하도록 만드는 것이 목적이라고 하네요. 간단하게, matpllitb의 그래픽을 html코드로(코드를 뜯어보면, 사실 거의 d3js 코드입니다만), 변환해줍니다. 이걸 가지고, 차트 같은 것을 좀 더 편하게 변환할 수 있겠죠.

do it.Permalink

  • 다음처럼 figure를 만들고, 그 figure를 html로 내뱉으면 됩니다.
    • html을 저장하든(save_html), 결과를 스트링으로 가져오든 뭘하든 간에 맥에서는 잘 작동하지 않습니다.
!pip install mpld3

import json
import mpld3
import matplotlib.pyplot as plt

f = plt.figure()
plt.plot([1,2,3], [4,5,6])

print(mpld3.fig_to_html(f, figid='THIS_IS_FIGID'))

  • 아래처럼 html 페이지로 만들어집니다.
<style>

</style>

<div id="THIS_IS_FIGID"></div>
<script>
function mpld3_load_lib(url, callback){
  var s = document.createElement('script');
  s.src = url;
  s.async = true;
  s.onreadystatechange = s.onload = callback;
  s.onerror = function(){console.warn("failed to load library " + url);};
  document.getElementsByTagName("head")[0].appendChild(s);
}

if(typeof(mpld3) !== "undefined" && mpld3._mpld3IsLoaded){
   // already loaded: just create the figure
   !function(mpld3){
       
       mpld3.draw_figure("THIS_IS_FIGID", {"width": 576.0, "height": 396.0, "axes": [{"bbox": [0.125, 0.125, 0.775, 0.755], "xlim": [0.9, 3.1], "ylim": [3.9, 6.1], "xdomain": [0.9, 3.1], "ydomain": [3.9, 6.1], "xscale": "linear", "yscale": "linear", "axes": [{"position": "bottom", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}, {"position": "left", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}], "axesbg": "#EAEAF2", "axesbgalpha": null, "zoomable": true, "id": "el149140466966796328", "lines": [{"data": "data01", "xindex": 0, "yindex": 1, "coordinates": "data", "id": "el149140466967383568", "color": "#4C72B0", "linewidth": 1.75, "dasharray": "none", "alpha": 1, "zorder": 2, "drawstyle": "default"}], "paths": [], "markers": [], "texts": [], "collections": [], "images": [], "sharex": [], "sharey": []}], "data": {"data01": [[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]}, "id": "el149140466979442984", "plugins": [{"type": "reset"}, {"type": "zoom", "button": true, "enabled": false}, {"type": "boxzoom", "button": true, "enabled": false}]});
   }(mpld3);
}else if(typeof define === "function" && define.amd){
   // require.js is available: use it to load d3/mpld3
   require.config({paths: {d3: "https://mpld3.github.io/js/d3.v3.min"}});
   require(["d3"], function(d3){
      window.d3 = d3;
      mpld3_load_lib("https://mpld3.github.io/js/mpld3.v0.3.js", function(){
         
         mpld3.draw_figure("THIS_IS_FIGID", {"width": 576.0, "height": 396.0, "axes": [{"bbox": [0.125, 0.125, 0.775, 0.755], "xlim": [0.9, 3.1], "ylim": [3.9, 6.1], "xdomain": [0.9, 3.1], "ydomain": [3.9, 6.1], "xscale": "linear", "yscale": "linear", "axes": [{"position": "bottom", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}, {"position": "left", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}], "axesbg": "#EAEAF2", "axesbgalpha": null, "zoomable": true, "id": "el149140466966796328", "lines": [{"data": "data01", "xindex": 0, "yindex": 1, "coordinates": "data", "id": "el149140466967383568", "color": "#4C72B0", "linewidth": 1.75, "dasharray": "none", "alpha": 1, "zorder": 2, "drawstyle": "default"}], "paths": [], "markers": [], "texts": [], "collections": [], "images": [], "sharex": [], "sharey": []}], "data": {"data01": [[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]}, "id": "el149140466979442984", "plugins": [{"type": "reset"}, {"type": "zoom", "button": true, "enabled": false}, {"type": "boxzoom", "button": true, "enabled": false}]});
      });
    });
}else{
    // require.js not available: dynamically load d3 & mpld3
    mpld3_load_lib("https://mpld3.github.io/js/d3.v3.min.js", function(){
         mpld3_load_lib("https://mpld3.github.io/js/mpld3.v0.3.js", function(){
                 
                 mpld3.draw_figure("THIS_IS_FIGID", {"width": 576.0, "height": 396.0, "axes": [{"bbox": [0.125, 0.125, 0.775, 0.755], "xlim": [0.9, 3.1], "ylim": [3.9, 6.1], "xdomain": [0.9, 3.1], "ydomain": [3.9, 6.1], "xscale": "linear", "yscale": "linear", "axes": [{"position": "bottom", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}, {"position": "left", "nticks": 11, "tickvalues": null, "tickformat": null, "scale": "linear", "fontsize": 10.0, "grid": {"gridOn": true, "color": "#FFFFFF", "dasharray": "none", "alpha": 1.0}, "visible": true}], "axesbg": "#EAEAF2", "axesbgalpha": null, "zoomable": true, "id": "el149140466966796328", "lines": [{"data": "data01", "xindex": 0, "yindex": 1, "coordinates": "data", "id": "el149140466967383568", "color": "#4C72B0", "linewidth": 1.75, "dasharray": "none", "alpha": 1, "zorder": 2, "drawstyle": "default"}], "paths": [], "markers": [], "texts": [], "collections": [], "images": [], "sharex": [], "sharey": []}], "data": {"data01": [[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]}, "id": "el149140466979442984", "plugins": [{"type": "reset"}, {"type": "zoom", "button": true, "enabled": false}, {"type": "boxzoom", "button": true, "enabled": false}]});
            })
         });
}
</script>

wrap-upPermalink

  • mpld3 example gallery에 들어가면 그 외에도 다양한 예제들이 있습니다만, 이걸 다 정확하게 이해하려면 d3js를 잘 알아야 하는 것 같습니다.
  • 또한 아쉽게도 networkx를 통해서 그린 그림에 대해서는 잘 만들어주지 않습니다. 결국 이건 다른 라이브러리를 사용해서 변환하는 쪽으로 생각해야 할 것 같아요. 정 안되면, 그냥 svg로 만들어서 뿌려주는 것이 가장 효과적인 것 같습니다.

 

 

반응형
반응형

mpld3 - Bringing Matplotlib to the Browser

https://mpld3.github.io/install.html

 

Installing mpld3 — Bringing Matplotlib to the Browser

Dependencies The mpld3 package is compatible with Python versions 2.6, 2.7, 3.3, and 3.4. It requires matplotlib version 1.3+ and jinja2 version 2.7+. Optionally, mpld3 can be used within the IPython notebook, and requires IPython version 1.0+, and prefera

mpld3.github.io

 mpld3는 매트플롯립과 d3js를 사용해서 웹의 인터랙티브 데이터 시각화 를 가능하도록 만드는 것이 목적이라고 하네요. 간단하게, matpllitb의 그래픽을 html코드로(코드를 뜯어보면, 사실 거의 d3js 코드입니다만), 변환해줍니다. 이걸 가지고, 차트 같은 것을 좀 더 편하게 변환할 수 있겠죠.

https://anaconda.org/conda-forge/mpld3

Installers

Info: This package contains files in non-standard labels.

conda install 

  •  linux-64  v0.3
  •  win-32  v0.3
  •    noarch  v0.5.7
  •  osx-64  v0.3
  •  win-64  v0.3
To install this package with conda run one of the following:
conda install -c conda-forge mpld3
conda install -c conda-forge/label/gcc7 mpld3
conda install -c conda-forge/label/cf201901 mpld3
conda install -c conda-forge/label/cf202003 mpld3
반응형

+ Recent posts