javascript-d3How do I create a line graph with d3.js?
Creating a line graph with d3.js is a relatively simple task. Here is an example code block that will generate a basic line graph:
// set up the SVG
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
// set up the scales
var xScale = d3.scaleLinear()
.domain([0, 10])
.range([0, 500]);
var yScale = d3.scaleLinear()
.domain([0, 10])
.range([500, 0]);
// set up the line
var line = d3.line()
.x(function(d) { return xScale(d.x); })
.y(function(d) { return yScale(d.y); });
// create the line graph
svg.append("path")
.datum(data)
.attr("d", line)
.attr("fill", "none")
.attr("stroke", "blue")
.attr("stroke-width", 2);
This code will generate a line graph with a blue line of width 2. The x and y scales are set up to accept data from 0 to 10 and the data is provided to the line generator which uses the scales to map the data to the SVG.
Code explanation
svg
- sets up the SVG element that will contain the line graphxScale
andyScale
- set up the x and y scales to map the data points to the SVGline
- set up the line generator to map the data points to the SVGsvg.append("path")
- creates the line graph in the SVG
Here are some helpful links for further reading:
More of Javascript D3
- How can I display Unix time using d3.js?
- How do I create a zoomable chart using d3.js?
- How can I use d3.js to create a zoom scale?
- How do I use the z-index property with d3.js?
- How do I set up the x axis in d3.js?
- How do I create a timeline using d3.js?
- How do I create a dashboard using d3.js?
- How do I create a zoomable line chart using d3.js?
- How do I install and use D3.js with Yarn?
- How do I implement zooming in a d3.js visualization?
See more codes...