@lily
To make a horizontal stacked bar chart with d3.js, follow these steps:
- Prepare the data: Create an array of objects with the data you want to visualize. Each object in the array represents a category, and should include keys for the category name and values for each stack in the bar chart.
1
2
3
4
5
6
|
var data = [
{ category: "Category 1", stack1: 20, stack2: 30, stack3: 10 },
{ category: "Category 2", stack1: 40, stack2: 15, stack3: 25 },
{ category: "Category 3", stack1: 10, stack2: 5, stack3: 30 },
// ...
];
|
- Set up the SVG container: Create an SVG container to hold the bar chart and set its width and height.
1
2
3
4
5
6
7
|
var svgWidth = 500;
var svgHeight = 300;
var svg = d3.select("body")
.append("svg")
.attr("width", svgWidth)
.attr("height", svgHeight);
|
- Define the scales: Determine the scales for the x-axis and y-axis.
1
2
3
4
5
6
7
8
9
10
11
12
|
var xScale = d3.scaleLinear()
.domain([0, d3.max(data, function(d) {
return d3.sum(Object.values(d));
})])
.range([0, svgWidth]);
var yScale = d3.scaleBand()
.domain(data.map(function(d) {
return d.category;
}))
.range([0, svgHeight])
.padding(0.1);
|
- Create the bars: Bind the data to the bars and append rectangles to represent each stack in the bar chart.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
var bars = svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", 0)
.attr("y", function(d) {
return yScale(d.category);
})
.attr("width", function(d) {
return xScale(d3.sum(Object.values(d)));
})
.attr("height", yScale.bandwidth())
.attr("fill", function(d) {
// Set individual stack colors here
});
|
- Add labels: Add labels to the bars to display the values of each stack.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
var labels = svg.selectAll("text")
.data(data)
.enter()
.append("text")
.text(function(d) {
return Object.values(d).slice(1).join(", ");
})
.attr("x", function(d) {
return xScale(d3.sum(Object.values(d))) + 5;
})
.attr("y", function(d) {
return yScale(d.category) + yScale.bandwidth() / 2;
})
.attr("dy", "0.35em");
|
Remember to customize the colors, styles, and other attributes according to your needs.