Putting Multiple d3 Charts on One Page
I wanted to put multiple d3 charts on one page, but I couldn’t find any examples that I liked. All of the examples on the internet expected you to know how many charts you wanted to put on the page to begin with. And I wanted to put one chart for each dataset, and I didn’t know how many datasets there would be.
So I spent today making a basic example that I can modify later. Again, this is another case of my putting this here so that I have a better chance of finding it in the future when I need it.
Each chart should be attached to its own element of the page. It made sense to me to
give each chart its own <div>
. Each of my <div>
s is named something like chart0
,
chart1
, etc., and it’s created as I loop over the array of datasets. I then toss the
name of the <div>
and the dataset to my chart-drawing function, and then I have
some charts. Whee.
And that is what I did today while the world burned.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Some Rectangles</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
// Where do I draw the chart? With which data?
function drawChart(dom, thedata){
//Width and height
var w = 500;
var h = 100;
var color = ["DarkOrange", "SteelBlue"];
var dataset = thedata;
//Create SVG element
var svg = d3.select(dom)
.append("svg")
.attr("width", w)
.attr("height", h);
// My charts are made out of two rectangles each
var rectangles = svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect");
rectangles.attr("x", function(d, i) {
return d[0];
})
.attr("y", 0)
.attr("width", function(d){
return d[1];
})
.attr("height", h)
.attr("fill", function(d, i){
return color[i];
});
}
</script>
<style type="text/css">
/* STYLE! */
html * {font-family: sans-serif;}
</style>
</head>
<body>
<?php
// Add more data, and there will be more charts!
// These data represent the horizontal extents of my rectangles
$all_my_data = array("[[0, 200], [200, 500]]",
"[[0, 100], [100, 500]]",
"[[0, 400], [400, 500]]"
);
echo '<div id="container">';
echo '<h1>Let\'s make some charts!</h1>';
foreach($all_my_data as $i => $item){
echo '<h2>This is chart '. $i .'</h2>';
echo '<div id="chart'.$i.'"></div>';
echo '<script>';
echo 'var myDOM = "#chart'.$i.'";';
echo 'var mydata = '. $all_my_data[$i] .';';
echo 'drawChart(myDOM, mydata);';
echo '</script>';
}
echo '</div>';
?>
</body>
</html>