Published
Edited
Feb 21, 2020
4 forks
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("Minutes");
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, 300])
//.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, 301, 30)))
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

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