How to create a stacked barchart using d3.js?

Member

by rollin , in category: Javascript , 6 months ago

How to create a stacked barchart using d3.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 6 months ago

@rollin 

To create a stacked barchart using d3.js, you can follow these steps:


Step 1: Include the d3.js library in your HTML file. You can do this by adding the following script tag to your HTML file:

1
<script src="https://d3js.org/d3.v7.min.js"></script>


Step 2: Create an SVG element in your HTML file where the stacked barchart will be displayed:

1
<svg id="chart"></svg>


Step 3: Create a dataset for your stacked barchart. This dataset should be an array of objects, where each object represents a category and contains an array of values for each stack within that category.


Step 4: Use d3.js to bind the dataset to rectangles in the SVG element and create the stacked barchart. Here is an example code snippet to create a stacked barchart:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const dataset = [
  {category: 'A', values: [10, 20, 30]},
  {category: 'B', values: [5, 15, 25]},
  {category: 'C', values: [8, 12, 20]}
];

const width = 500;
const height = 300;

const svg = d3.select('#chart')
              .attr('width', width)
              .attr('height', height);

const xScale = d3.scaleBand()
                .domain(dataset.map(d => d.category))
                .range([0, width])
                .padding(0.1);

const yScale = d3.scaleLinear()
                .domain([0, d3.max(dataset, d => d3.sum(d.values))])
                .range([height, 0]);

const colors = d3.scaleOrdinal(d3.schemeCategory10);

svg.selectAll('g')
    .data(dataset)
    .enter().append('g')
    .attr('fill', d => colors(d.category))
  .selectAll('rect')
    .data(d => d.values)
    .enter().append('rect')
    .attr('x', (d, i) => xScale(dataset[i].category))
    .attr('y', d => yScale(d + d3.sum(dataset, d => d3.sum(d.values.slice(0, d.index)))))
    .attr('width', xScale.bandwidth())
    .attr('height', d => yScale(d3.sum(dataset, d => d3.sum(d.values.slice(0, d.index + 1))) - d3.sum(dataset, d => d3.sum(d.values.slice(0, d.index))));  


This code snippet will create a simple stacked barchart with three categories (A, B, C) and three values for each category. Feel free to customize the code to fit your dataset and styling preferences.