Published
Edited
Sep 22, 2022
2 forks
2 stars
Insert cell
Insert cell

chart = {
const svg = d3.create('svg')
.attr('viewBox', [0, 0, width, height])
.attr('style', 'border: 1px solid #eee')
.attr('xmlns', 'http://www.w3.org/2000/svg')
svg.call(xAxis);
svg.call(yAxis)

svg.append("g")
.selectAll('g')
.data(chartData)
.join("g")
.style('fill', (d, i) => {
const c = d3.color(color(d.key));
const start = c.toString();
c.opacity = 0.4;
const end = c.toString();
gradient(svg, d.key, start, end);
// return color(d.key)
return `url(#${d.key})`
})
// Stack
.selectAll('rect')
.data(d => {
return d;
})
.join('rect')
.attr('x', d => xScale(d.data.xKey))
.attr('y', d => yScale(d[1]))
.attr('height', d => yScale(d[0]) - yScale(d[1]))
.attr('width', xScale.bandwidth())
// .attr('fill', 'url(#mylLnearGradient)');
return svg.node();
}

Insert cell
chartData = d3.stack().keys(stack.categories)(stack.data)
Insert cell
Insert cell
xAxis = svg => svg.append("g")
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(xScale).tickSizeOuter(0))
Insert cell
yAxis = svg => {
// A helper method for generating grid lines on the y-axis.
function grid(tick) {
return tick.append("line")
.attr("class", "grid")
.attr("x2", width - margin.left - margin.right)
.attr("stroke", "rgba(0,0,0,0.2)")
// .attr("stroke-opacity", 0.5)
.attr("stroke-dasharray", [5, 5])
}

return svg.append("g")
.attr("transform", `translate(${margin.left}, 0)`)
.call(d3.axisLeft(yScale).ticks(5))
// .call(svg => svg.select(".domain").remove())
.call(g => g.selectAll(".tick").call(grid));
}

Insert cell
xScale = {
const domains = xDomains;

const scale = d3.scaleBand()
.range([margin.left, width - margin.right])
.domain(domains)
.paddingInner(0.1)
.paddingOuter(0.1);
return scale;
}
Insert cell
yScale = {
const min = d3.min(stack.data, (d) => d.total);
const max = d3.max(stack.data, (d) => d.total);

const scale = d3.scaleLinear()
.domain([0, max])
.nice()
.clamp(true)
.range([height - margin.bottom, margin.top]);
return scale;
}
Insert cell
color = d3.scaleOrdinal(
stack.categories,
colors[1]
)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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