Public
Edited
Apr 1, 2024
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
// settings for our pie chart
const w = 600;
const h = 500;

// create our SVG element
const svg = d3.create("svg").attr("width", w).attr("height", h);

// create a scale for y-axis
const yScale = d3
.scaleLinear()
.domain([
0,
d3.max(stackedBarDataset, (d) => d.Foxhole + d.LeagueOfLegends + d.LostArk + d.Squad)
])
.range([h - 40, 20]);

const xScale = d3
.scaleBand()
.domain(stackedBarDataset.map((d) => d.date))
.range([60, w - 20])
.padding(0.05);

const cScale = d3.scaleOrdinal(d3.schemePastel1);

const stack = d3.stack().keys(["Foxhole", "LeagueOfLegends", "LostArk", "Squad"]);
debugger;
const groups = svg
.selectAll("g")
.data(stack(stackedBarDataset))
.join("g")
.style("fill", (d, i) => cScale(i));

groups
.selectAll("rect")
.data((d) => d)
.join("rect")
.attr("x", (d) => xScale(d.data.date))
.attr("y", (d) => yScale(d[1]))
.attr("width", xScale.bandwidth())
.attr("height", (d) => yScale(d[0]) - yScale(d[1]));

const xAxis = d3
.axisBottom(xScale)
.ticks(stackedBarDataset.length + 1)
.tickFormat(d3.timeFormat("%b"));

svg
.append("g")
.attr("class", "stacked-x-axis")
.attr("transform", `translate(0, ${h - 40})`)
.call(xAxis);

const yAxis = d3.axisLeft(yScale);

svg
.append("g")
.attr("class", "stacked-y-axis")
.attr("transform", `translate(60, 0)`)
.call(yAxis);

svg
.append("text")
.classed("axis-label", true)
.attr("transform", "rotate(-90)")
.attr("x", -h / 2 + 10)
.attr("y", 30)
.attr("text-anchor", "middle")
.text("Total hours played");

svg
.append("text")
.classed("axis-label", true)
.attr("x", w / 2 + 20)
.attr("y", h - 5)
.attr("text-anchor", "middle")
.text("2024");

const legendScale = d3
.scaleOrdinal()
.domain(["Foxhole", "LeagueOfLegends", "LostArk", "Squad"])
.range(d3.schemePastel1);

svg
.append("g")
.attr("class", "legendOrdinal")
.attr("transform", "translate(80,20)");

const legendOrdinal = d3Legend
.legendColor()
.shape("path", d3.symbol().type(d3.symbolSquare).size(80)())
.shapePadding(20)
.scale(legendScale);

svg.select(".legendOrdinal").call(legendOrdinal);

return svg.node();
}
Insert cell
Insert cell
Insert cell
d3Legend = require('d3-svg-legend')
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