Fit a plot in a div's max height

Viewed 5556

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?

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

Just add a new div around the #plotdiv. Try out the following code.

<div style="max-height:300px">
    <div id="plotDiv" style="width:100%">
    </div>
</div>
Related