Notebooks 2.0 is here.

Published
Edited
Aug 12, 2020
Insert cell
md`# split bar chart`
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
const splitBarCount = data[0];
const groups = svg.append("g")
.attr("fill", color)
.selectAll("g")
.data(data)
.join("g")
.attr("transform", (d, i) => "translate(0," + yAxis(d) + ")")
.attr('class', 'split-bar-group')
.each(function (d, idx) {
const bars = d3.select(this)
.selectAll('rect')
.data(d => d)
.join("rect")
.attr('class', 'split-bar-group-rect')
.attr("x", (d, i) => xAxis(i))
.attr("height", yAxis.bandwidth())
.attr("fill", (d, i) => colors[i])
.attr("width", (d,i) => nestedScales[i](d));
bars.append("text")
.text( function (d) { return d })
.attr("x", (d, i) => xAxis(i + 1) - 10)
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "red");
})
.append("g")
.call(d3.axisLeft(yAxisLabels))
return svg.node();
}
Insert cell
yAxisLabels = d3.scaleBand()
.range([ 0, height ])
.domain(months)
.padding(.1);
Insert cell
yAxis = d3.scaleBand()
.range([ 0, height ])
.domain(data)
.padding(.1);
Insert cell
console.log(yAxis(data[3]))
Insert cell
xAxis = d3.scaleBand()
.domain(d3.range(data[0].length))
.range([margin.left, width - margin.right])
.padding(0.1);
Insert cell
nestedScales = {
const nestedArrayLen = data[0].length;
let scales = [];
for(var i = 0; i < nestedArrayLen; i++) {
scales.push(d3.scaleLinear()
.domain([0, d3.max(data.flatMap(d => d[i]))]).nice()
.range([margin.left, ((width - margin.right)/ nestedArrayLen) - 60]))
}
console.log(scales)
return scales;
}
Insert cell
data = [[35,90], [60,45], [80,90], [95,90], [100,100]]

Insert cell
months = ["Jan - 20", "Feb - 20", "Mar - 20", "Apr -20"]
Insert cell
d3 = require("d3@5")
Insert cell
margin = ({top: 30, right: 0, bottom: 30, left: 40})
Insert cell
height = 300
Insert cell
color = "steelblue"
Insert cell
colors = ["black", "purple"]
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