chart = {
const margin = {top: 30, right: 30, bottom: 40, left: 160};
const width = 1000;
const height = 1200;
const svg = d3.create("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("viewBox", [0, 0, width + margin.left + margin.right, height + margin.top + margin.bottom])
.attr("style", "max-width: 100%; height: auto;");
const g = svg.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
const x = d3.scaleTime()
.domain(d3.extent(data, d => d.date))
.range([0, width]);
g.append("g")
.attr("transform", `translate(0,${height-80})`)
.call(d3.axisBottom(x)
.tickFormat(d3.timeFormat("%Y")));
g.append("text")
.attr("x", width / 2)
.attr("y", height-40)
.attr("text-anchor", "middle")
.style("font-size", "14px")
.text("Year");
let yPosition = 0;
countries.forEach(country => {
const countryData = dataByCountry.get(country);
const countryHeight = 50;
const y = d3.scaleLinear()
.domain([0, d3.max(countryData, d => d.mean_SD) * 1.5
])
.range([countryHeight, 0]);
g.append("text")
.attr("x", -160)
.attr("y", yPosition + countryHeight / 2)
.attr("alignment-baseline", "middle")
.style("font-size", "14px")
.text(country);
g.append("text")
.attr("x", -25)
.attr("y", yPosition + countryHeight / 2)
.attr("text-anchor", "middle")
.attr("transform", `rotate(-90, -25, ${yPosition + countryHeight / 2})`)
.style("font-size", "10px")
.style("font-weight", "bold")
.style("fill", "#555")
.text("mean_SD");
g.append("g")
.attr("transform", `translate(0, ${yPosition})`)
.call(d3.axisLeft(y)
.ticks(2)
.tickSize(0))
.call(g => g.select(".domain").remove());
g.append("path")
.datum(countryData)
.attr("fill", "none")
.attr("stroke", "#3182bd")
.attr("stroke-width", 1.5)
.attr("transform", `translate(0,${yPosition})`)
.attr("d", d3.line()
.x(d => x(d.date))
.y(d => y(d.mean_SD)));
g.append("line")
.attr("x1", -20)
.attr("x2", width)
.attr("y1", yPosition + countryHeight + 10)
.attr("y2", yPosition + countryHeight + 10)
.attr("stroke", "lightgrey")
.attr("stroke-width", 1);
yPosition += countryHeight + 20;
});
svg.append("text")
.attr("x", width / 2 + margin.left)
.attr("y", 20)
.attr("text-anchor", "middle")
.style("font-size", "24px")
.style("font-weight", "bold")
.text("Dynamics of precipitation over time");
svg.append("text")
.attr("x", width-60)
.attr("y", height)
.style("font-size", "12px")
.style("font-style", "italic")
.text("Data source: Era5, https://www.ecmwf.int/");
return svg.node();
}