Public
Edited
Apr 23, 2023
Insert cell
Insert cell
svg = {
let yearIndex = 0;
let yearData = data.filter(d => d.year === years[yearIndex])
.sort(yearSort);
y.domain(yearData.map(d => d.city));
let svg = d3.select(DOM.svg(width, height))
.attr("font-family", fontFamily);
let gView = svg.append("g")
.classed("view", true)
.attr("transform", `translate(${margin.left}, ${margin.top})`);
// Draw the bars.
let bars = gView.selectAll("rect")
.data(yearData)
.join("rect")
.attr("fill", "#f38051")
.attr("x", 0)
.attr("y", d => y(d.city))
.attr("width", d => x(d.cost))
.attr("height", y.bandwidth());
// Draw the title.
let title = svg.append("g")
.classed("title", true)
.attr("transform", `translate(${margin.left}, 0)`)
.append("text")
.classed("title", true)
.attr("y", titleFontSize)
.text(d => titleText(yearData));
svg.append("g")
.classed("x-axis", true)
.call(xAxis);
let gy = svg.append("g")
.classed("y-axis", true)
.call(yAxis);
setInterval(() => {
let t = svg.transition()
.duration(transitionDuration);
// Increment the year index. If the new index exceeds the length of the
// the number of years, then go back to index 0.
yearIndex++;
if (yearIndex >= years.length) {
yearIndex = 0;
}
let yearData = data.filter(d => d.year === years[yearIndex])
.sort(yearSort);
y.domain(yearData.map(d => d.city));
gy.transition(t)
.call(yAxis);
bars.data(yearData, d => d.city)
.attr('stroke', '#2c2c2c')
.attr('stroke-width', 2)
.transition(t)
.attr("y", d => y(d.city))
.attr("width", d => x(d.number_of_appointments));
// Update the title.
title.text(titleText(yearData));
}, timerInterval);
return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
color = (city) => {
let colors = cities.map((number_of_appointments, i) => {
return {
city: city,
color: d3.schemeSet2[i]
};
});
let found = colors.find(c => c.city === city);
return (found) ? found.color : "black";
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
fontFamily = "Arial, sans-serif"
Insert cell
titleText = (yearData) => {
let years = yearData[0].year;
let values = yearData.map(d => d.cost * 1e3);
let sum = d3.sum(values);
return `Number of scenic spots booked in Hunan in ${years}`
// return myTitle
}
Insert cell
titleFontSize = 16
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