Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@pikattoo

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

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>

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
5
Help us understand the problem. What are the problem?