Make Plotly figures responsive in Bootstrap by assigning class
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<title>Responsive Plotly Charts</title> | |
<!-- Bootstrap --> | |
<link href="/static/css/bootstrap.min.css" rel="stylesheet"> | |
<link href="/static/css/style.css" rel="stylesheet"> | |
<link rel="shortcut icon" href="/static/favicon.ico"> | |
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> | |
<!-- WARNING: Respond.js doesn't work if you view the page via file:// --> | |
<!--[if lt IE 9]> | |
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> | |
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> | |
<![endif]--> | |
</head> | |
<body> | |
<div class="container"> | |
<div class="row"> | |
<div class="col-md-6"> | |
<!-- ADD THE responsive-plot CLASS --> | |
<div id="plot1" class="responsive-plot"></div> | |
</div> | |
<div class="col-md-3"> | |
<!-- ADD THE responsive-plot CLASS --> | |
<div id="plot2" class="responsive-plot"></div> | |
</div> | |
<div class="col-md-3"> | |
<!-- ADD THE responsive-plot CLASS --> | |
<div id="plot3" class="responsive-plot"></div> | |
</div> | |
</div> | |
</div> | |
<script type="text/javascript" src="https://cdn.plot.ly/plotly-latest.min.js"></script> | |
<!-- CREATE THE RESPONSIVE PLOTLY PLOTS --> | |
<script src="my_plot_scripts.js"></script> | |
<script type="text/javascript" src="https://cdn.plot.ly/plotly-latest.min.js"></script> | |
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> | |
<!-- Include all compiled plugins (below), or include individual files as needed --> | |
<script src="/static/js/bootstrap.min.js"></script> | |
<script src="/static/js/scripts.js"></script> | |
</body> | |
</html> |
//create the Plotly plots | |
Plotly.newPlot("plot", data1); | |
Plotly.newPlot("plot2", data2); | |
Plotly.newPlot("plot3", data3); | |
// MAKE THE PLOTS RESPONSIVE | |
(function() { | |
var d3 = Plotly.d3; | |
var WIDTH_IN_PERCENT_OF_PARENT = 100, | |
HEIGHT_IN_PERCENT_OF_PARENT = 90; | |
var gd3 = d3.selectAll(".responsive-plot") | |
.style({ | |
width: WIDTH_IN_PERCENT_OF_PARENT + '%', | |
'margin-left': (100 - WIDTH_IN_PERCENT_OF_PARENT) / 2 + '%', | |
height: HEIGHT_IN_PERCENT_OF_PARENT + 'vh', | |
'margin-top': (100 - HEIGHT_IN_PERCENT_OF_PARENT) / 2 + 'vh' | |
}); | |
var nodes_to_resize = gd3[0]; //not sure why but the goods are within a nested array | |
window.onresize = function() { | |
for (var i = 0; i < nodes_to_resize.length; i++) { | |
Plotly.Plots.resize(nodes_to_resize[i]); | |
} | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment