Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d3
javascript
data visualization

How to create a bar chart using D3

Educative Answers Team
svg viewer

A bitabout D3

D3 is an interactive JavaScript library for data visualization. It uses Scalar Vector Graphics (SVG) coupled with HTML and CSS to display charts and figures that illustrate the numeric data. You can also use D3 to plot bar charts. The following is a step by step guide on how to print bar charts using D3.

Step 1: Dataset

Before even starting to code, we need a data set to base our chart on. For this example, we will take a basic array of sales total and show them in a bar graph. Our array is [33, 57, 84, 21, 60].

Step 2: D3 and SVG container

The first thing we need to do is import the D3 script using the src attribute, and then initialize our SVG container with the appropriate width and height.

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="500" height="400"></svg>

Step 3: Set margin

To make the chart look more centered and clear, we need to set a margin for our SVG. We are making 4 variables; svg, margin, width, and height. svg is initialized with the 500px width and 400px height. These widths and heights are then adjusted according to the 200px margin.

var svg = d3.select("svg"),
            margin = 200,
            width = svg.attr("width") - margin,
            height = svg.attr("height") - margin

Step 4: Set scale

For discrete data visualization on the x-axis, we construct a Band Scale or scaleBand(). scaleBand() makes discrete bands for our values on the x-axis and then induces padding to separate the bars in the bar chart.

For our y-axis, we use Linear Scale or scaleLinear() to show the sales.

var xScale = d3.scaleBand().range([0, width]).padding(0.5),
            yScale = d3.scaleLinear().range([height, 0]);

Step 5: Set domain

We need to set the domain for both of our axes. For the x-axis, we are using the dataset as the domain itself. You can make another array and set it as the domain. For y-axis, we are setting a range from 0 to 100.

xScale.domain(dataset1);
        yScale.domain([0, 100]);

Step 6: Format axis

Our sales is in dollars ($ ), therefore, we are setting the y-axis to display the sales total with the dollar sign. We are also adding "sale: " to each sale value in the x-axis for clarity.

g.append("g")
         .attr("transform", "translate(0," + height + ")")
         .call(d3.axisBottom(xScale).tickFormat(function(d){
           return "sale: " + d;
         })
         );

        g.append("g")
         .call(d3.axisLeft(yScale).tickFormat(function(d){
             return "$" + d;
         }).ticks(4));

Step 7: Create bars

This is where the magic happens. First, we create dynamic bars.

g.selectAll(".bar")
         .data(dataset1)
         .enter().append("rect")

Then, we place the bars on their correct x-y position using the xScale and yScale created earlier. Next, we describe the width and height of the bars.

g.selectAll(".bar")
         .data(dataset1)
         .enter().append("rect")
         .attr("class", "bar")
         .attr("x", function(d) { return xScale(d); })
         .attr("y", function(d) { return yScale(d); })
         .attr("width", xScale.bandwidth())
         .attr("height", function(d) { return height - yScale(d); });

Final code

Combining all the above steps, we will get something like this:

RELATED TAGS

d3
javascript
data visualization
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring