Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit a plot in a div's max height

I am trying a plot in a div using plotly.js which is a bit large in height. I want to fit it to div's height. If I use

<div id="plotDiv"></div>

and

var trace1 = {
            x: ['giraffes', 'orangutans', 'monkeys'],
            y: [20, 14, 23],
            name: 'SF Zoo',
            type: 'bar'
        };

        var trace2 = {
            x: ['giraffes', 'orangutans', 'monkeys'],
            y: [12, 18, 29],
            name: 'LA Zoo',
            type: 'bar'
        };

        var data = [trace1, trace2];

        var layout = {
            autosize:true,
            barmode: 'stack',
            xaxis: {
                tickangle: -45
            },
        };

        Plotly.newPlot('plotDiv', data, layout);

The plot is a bit large in height, so i put a max-height in div, this way :

<div id="plotDiv" style="max-height:300px"></div>

But this doesn't fit the plot in the div, and hides some of the plot. How to fit the complete plot in the div?

like image 688
Dreams Avatar asked Nov 08 '17 11:11

Dreams


1 Answers

As suggested by someone, (who had deleted his answer later on, before I could try and accept his answer), following the link here: example, I was able to resize the plot, :

var approved = {
                x: approvedX,
                y: approvedY,
                name: 'Approved',
                type: 'bar'
            };

            var unApproved = {
                x: unApprovedX,
                y: unApprovedY,
                name: 'UnApproved',
                type: 'bar'
            };

            var data = [approved, unApproved];

            var layout = {
                barmode: 'stack',
                xaxis: {
                    tickangle: -20
                },
                // title: 'Applications Comparison'
            };
            // Plotly.newPlot('plotDiv', data, layout);

            var d3 = Plotly.d3;

            var HEIGHT_IN_PERCENT_OF_PARENT = 80;

            var gd3 = d3.select('#plot2').append('div').style({
                 height: HEIGHT_IN_PERCENT_OF_PARENT + 'vh',
                'margin-top': 0 + 'vh',
                'margin-bottom': 10 + 'vh'
            });

            var gd = gd3.node();
            Plotly.plot(gd, data, layout);
            window.onresize = function() {
                Plotly.Plots.resize(gd);
            };

where approvedX, approvedY, unApprovedX, unApprovedY are lists.

like image 131
Dreams Avatar answered Oct 10 '22 19:10

Dreams