Published
Edited
May 6, 2021
Fork of Stacked-Bar
Insert cell
Insert cell
Insert cell
chart = {
// Main SVG
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
// SVG Group containing all bars
const bars = svg.append("g")
.attr("class", "bars");
// Array of SVG groups, each group is a series (same color)
const s = bars.selectAll("g").data(series)
.join("g")
.attr("class", "series")
.attr("fill", d => color(d.key)) // Color defined below
.selectAll("rect") // Individual boxes in each series
.data(d => d)
.join("rect") //recall (0,0) is top left corner, thus:
.attr("x", d => x(d.data.day))
.attr("y", d => y(d[1])) //y-coordinate determined by top of bar
.attr("height", d => y(d[0]) - y(d[1])) //height is bottom - top
.attr("width", x.bandwidth())
.append("title") //Useful for tooltips/accessibility.
.text(d => `${d.data.day} ${d.key}: ${d.data[d.key]} hours`);
//Axes
const xAx = svg.append("g").call(xAxis);
const yAx = svg.append("g").call(yAxis);
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -5)
.attr("x", -height/2)
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Hours");
return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
x = d3.scaleBand()
.domain(data.map(d => d.day))
.range([margin.left, width-margin.right])
.padding(0.5)
Insert cell
y = d3.scaleLinear()
.domain([0, 60])
//.domain([0, d3.max(series, d => d3.max(d, d => d[1]))])
.rangeRound([height-margin.bottom, margin.top])
Insert cell
Insert cell
xAxis = g => g
.attr("transform", `translate(0, ${height - margin.bottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0))
// .call(g => g.selectAll(".domain").remove()) //Gets rid of border line
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).tickValues(d3.range(0, 60,5)))
Insert cell
Insert cell
height = 600;
Insert cell
margin = ({top: 10, right: 10, bottom: 20, left: 40})
Insert cell
Insert cell
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more