areachart = {
const width = 928;
const height = 500;
const marginTop = 10;
const marginRight = 10;
const marginBottom = 20;
const marginLeft = 40;
const group = d3.rollup(
data,
v => v.length,
d => +d.Pclass,
d => d.Sex.toLowerCase().trim()
);
const pclass = [1, 2, 3];
const sexes = ["male", "female"];
const stackedgroups = pclass.map(Pclass => {
const sexMap = group.get(Pclass) || new Map();
const entry = { Pclass };
for (const sex of sexes) {
entry[sex] = sexMap.get(sex) || 0;
}
return entry;
});
const keys = ["male", "female"];
const series = d3.stack()
.keys(keys)
(stackedgroups);// distinct series keys, in input order
// defines the x-axis
const x = d3.scalePoint()
.domain([1, 2, 3])
.range([marginLeft, width - marginRight]);
// defines the y-axis
const y = d3.scaleLinear()
.domain([0, d3.max(series, d => d3.max(d, d => d[1]))])
.nice()
.range([height - marginBottom, marginTop]);
// defines the color scheme for the male and female areas
const color = d3.scaleOrdinal()
.domain(series.map(d => d.key))
.range(d3.schemeTableau10);
// defines the area for the graph
const area = d3.area()
.x(d => x(d.data.Pclass))
.y0(d => y(d[0]))
.y1(d => y(d[1]));
// defines the svg container
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto;");
svg.append("g")
.attr("transform", `translate(${marginLeft}, 0)`)
.call(d3.axisLeft(y).ticks(height / 80))
.call(g => g.select(".domain").remove())
.call(g => g.selectAll(".tick line").clone()
.attr("x2", width - marginLeft - marginRight)
.attr("stroke-opacity", 0.1))
.call(g => g.append("text")
.attr("x", -marginLeft)
.attr("y", 10)
.attr("fill", "currentColor")
.attr("text-anchor", "start")
.text("↑ Persons in a designated class"));
svg.append("g")
.selectAll()
.data(series)
.join("path")
.attr("fill", d => color(d.key))
.attr("d", area)
.append("title")
.text(d => d.key);
svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(d3.axisBottom(x).tickSizeOuter(0).tickFormat(d => `Class ${d}`));
// adds a legend to the area chart
const legend = svg.append("g")
.attr("transform", `translate(${width - marginRight - 150}, ${marginTop})`)
.selectAll("g")
.data(series)
.join("g")
.attr("transform", (d, i) => `translate(0, ${i * 20})`);
legend.append("rect")
.attr("width", 15)
.attr("height", 15)
.attr("fill", d => color(d.key));
legend.append("text")
.attr("x", 20)
.attr("y", 12)
.attr("fill", "currentColor")
.text(d => d.key);
return Object.assign(svg.node(), {scales: {color}});
}