Simple line chart that displays three dimensions of data taken from an accelerometer.
This is meant to be a very basic example of using a d3 line chart, while plotting multiple lines.
Note: some of the syntax has been simplified using ES6 arrow functions.
Built with blockbuilder.org
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.line {
fill: none;
opacity: 0.9;
stroke-width: 1.5px;
}
.line--x {
stroke: steelblue;
}
.line--y {
stroke: red;
}
.line--z {
stroke: purple;
}
</style>
</head>
<body>
<script>
// set the dimensions and margins of the graph
var margin = {top: 20, right: 40, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// the different dimensions in the data
var dims = ['x', 'y', 'z'];
// set x-range
var x = d3.scaleLinear().range([0, width]);
// set the y-ranges
var Y = {}
dims.forEach(dim => {
Y[dim] = d3.scaleLinear().range([height, 0]);
});
// define the line functions for each dimension
var lines = {}
dims.forEach(dim => {
lines[dim] = d3.line()
.x(d => x(d.tick))
.y(d => Y[dim](d[dim]));
});
// create the svg object
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// process the data
d3.csv("accel-data.csv",(error, data) => {
if (error) throw error;
// Parse the data
data.forEach(d => {
d.tick = +d.tick;
d.x = +d.x;
d.y = +d.y;
d.z = +d.z;
});
// Set domain scales
x.domain(d3.extent(data, d => d.tick));
for(var dim of dims) {
Y[dim].domain(d3.extent(data, d => d[dim]));
}
// Draw Paths
for (var dim of dims) {
svg.append("path")
.data([data])
.attr("class", "line line--"+dim)
.attr("d", d => lines[dim](d));
}
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add the Y Axis (Note how we only need one axis)
svg.append("g")
.attr("class", "axisSteelBlue")
.call(d3.axisLeft(Y['x']));
});
</script>
</body>
https://d3js.org/d3.v4.min.js