Published
Edited
Jan 31, 2020
3 forks
Insert cell
Insert cell
{
yield html`
<div id="chart">
</div>`;
drawBars();
}
Insert cell
async function drawBars() {
const svg = d3.select("#chart")
.append("svg")
.attr("width", dimensions.width + dimensions.margin.left + dimensions.margin.right)
.attr("height", dimensions.height + dimensions.margin.top + dimensions.margin.bottom)
.append("g")
.attr("transform",
"translate(" + dimensions.margin.left + "," + dimensions.margin.top + ")")
svg.append("g")
.selectAll("g")
// Enter in the stack data = loop key per key = group per group
.data(stackedData)
.enter().append("g")
.attr("fill", d => color(d.key))
.selectAll("rect")
// enter a second time = loop subgroup per subgroup to add all rectangles
.data(d => d)
.enter().append("rect")
.attr("x", d => x(d.data.group))
.attr("y", d => y(d[1]))
.attr("height", d => y(d[0]) - y(d[1]))
.attr("width",x.bandwidth())
svg.append("g")
.attr("transform", "translate(0," + dimensions.height + ")")
.call(d3.axisBottom(x).tickSizeOuter(0));
svg.append("g")
.call(d3.axisLeft(y));
}
Insert cell
y = d3.scaleLinear()
.domain([0, 60])
.range([ dimensions.height, 0 ]);
Insert cell
x = d3.scaleBand()
.domain(groups)
.range([0, dimensions.width])
.padding([0.2])
Insert cell
color = d3.scaleOrdinal()
.domain(subgroups)
.range(['#9CADCE','#7EC4CF','#52B2CF'])
Insert cell
stackedData = d3.stack()
.keys(subgroups)
(data)
Insert cell
groups = d3.map(data, d => d.group).keys()
Insert cell
subgroups = data.columns.slice(1)
Insert cell
data = d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_stacked.csv")
Insert cell
dimensions = ({
height:400,
width:600,
margin: {
top: 10,
right: 30,
bottom: 20,
left: 50,
}
})
Insert cell
d3 = require("d3@5")
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more