javascript-d3How do I create a simple bar chart with D3.js in JavaScript?
To create a simple bar chart with D3.js in JavaScript, you can use the following code example:
// set up svg canvas
var svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
// set up data
var dataset = [ 5, 10, 15, 20, 25 ];
// set up scales
var xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.rangeRound([0, 500])
.paddingInner(0.05);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset)])
.range([500, 0]);
// set up bars
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return yScale(d);
})
.attr("width", xScale.bandwidth())
.attr("height", function(d) {
return 500 - yScale(d);
})
.attr("fill", "teal");
This code will generate a simple bar chart like this:
The code consists of the following parts:
- Setting up an SVG canvas to draw the chart on:
var svg = d3.select("body").append("svg").attr("width", 500).attr("height", 500);
- Setting up the data to be used in the chart:
var dataset = [ 5, 10, 15, 20, 25 ];
- Setting up the scales for the x and y axes:
var xScale = d3.scaleBand().domain(d3.range(dataset.length)).rangeRound([0, 500]).paddingInner(0.05);
var yScale = d3.scaleLinear().domain([0, d3.max(dataset)]).range([500, 0]);
- Setting up the bars of the chart:
svg.selectAll("rect").data(dataset).enter().append("rect")
.attr("x", function(d, i) { return xScale(i); })
.attr("y", function(d) { return yScale(d); })
.attr("width", xScale.bandwidth())
.attr("height", function(d) { return 500 - yScale(d); })
.attr("fill", "teal");
For more information on how to create bar charts with D3.js, please see the following links:
More of Javascript D3
- How do I use the z-index property with d3.js?
- How can I use d3.js to create an interactive mouseover effect?
- How do I create a zoomable chart using d3.js?
- How can I use d3.js and neo4j together to create data visualizations?
- How can I use d3.js to create a zoom scale?
- How do I create a zoomable line chart using d3.js?
- How do I implement zooming in a d3.js visualization?
- How can I use D3.js to read a CSV file?
- How do I use d3.js to implement zooming functionality?
- How do I install and use D3.js with Yarn?
See more codes...