8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Plotly + Flask + Python] HTML上でレスポンシブルなグラフ表示

Posted at

Bootstrap4でレスポンシブなCard配置ができた.
http://shoelace.io/

Plotlyで表示するグラフサイズがレスポンシブじゃない...

Pythonでは,以下のようにプログラムを書けば,Javascriptで表示するためのコードが得られる.

import plotly as py
import plotly.figure_factory as ff

fig = ff.create_gantt(ganttData, index_col='Order', title='Data Result',
                      colors=colors, show_colorbar=True, showgrid_x=True,
                      showgrid_y=True, group_tasks=True,
                      width="750", height="400")
graphJSON = json.dumps(fig, cls=py.utils.PlotlyJSONEncoder)

このgraphJSONを,render_htmlする際の引数に入れる.
あとは,受け取り側のHTMLに

<script>
    var graphs = {{ ganttPlotInfo | safe }};
    Plotly.plot('bargraph',graphs,{});
</script>

と書けば,表示できる.

ここで,HTMLのグラフを表示したい場所(BODY内)に

<script>
    var graphs = {{ ganttPlotInfo | safe }};
    window.addEventListener( "resize", function () {
        if ( window.innerWidth < 800 ) {
            graphs.layout.width=400;
            Plotly.newPlot('bargraph',graphs,{});
        } else if( window.innerWidth < 1200 ) {
            graphs.layout.width=600;
            Plotly.newPlot('bargraph',graphs,{});
        } else {
            graphs.layout.width=750;
            Plotly.newPlot('bargraph',graphs,{});
        }
    } ) ;
</script>

HEAD内に

<script>
    window.onload = function() {
                        alert(window.innerWidth);
                        if ( window.innerWidth < 800 ) {
                            graphs.layout.width=400;
                            Plotly.plot('bargraph',graphs,{});
                        } else if( window.innerWidth < 1200 ) {
                            graphs.layout.width=600;
                            Plotly.plot('bargraph',graphs,{});
                        } else {
                            graphs.layout.width=750;
                            Plotly.plot('bargraph',graphs,{});
                        }
                    };
</script>

をそれぞれ入れると,グラフサイズがレスポンシブになる.

プログラムはめちゃめちゃ,閾値も適当.
もっといい方法があるかもしれませんが,取り急ぎ.

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?