Bar Chart
Appending SVG Tags Programmatically
var svg = d3.select("body").append("svg")
.attr("id", "chart")
.attr("width", 800)
.attr("height", 450)Methodology:
html body selector -> appending DOM type -> defining attributes
Bar Chart, Basic Layout
var data = [132,71,337,93,78,43,20,16,30,8,17,21];
var svg = d3.select("body").append("svg")
.attr("id", "chart")
.attr("width", 800)
.attr("height", 450)
svg.selectAll(".bar") // attribute class
.data(data) // data source
.enter() // bind data
.append("rect") // append a rectangle for each element in data
.attr("class", "bar") // future attributes
.attr("x", 0) // x position
.attr("y", function(d, i) {
return 20 * i;
}) // y position stacked reletive to i
.attr("width", function(d, i) {
return d;
}) // scale width of bar occording to data
.attr("height", 19)
Bar Chart: Scaling
One way to do this mathematically:
But d3 make it easy for us!

Bar Chart: CSS Styling

Adding additional classes
Bar Chart: Adding Text

Bar Chart: Adding Flexibility with Chart Function
The goal of this next section is to try and make a convenient way to plot our data, and make our code a little bit more reusable.
To do so, we encapsulate it within a function that accept an object containing a data key value pair.
Bar Chart: Grouping Elements
To organize things a bit more, we can group all of our elements together
Here is our final product
I've also cleaned up somethings

Last updated
Was this helpful?