Public
Edited
Apr 16
Insert cell
Insert cell
viewof kickstarterLineChart = {
const container = html`<div id="line-chart"></div>`;

const margin = { top: 80, right: 120, bottom: 100, left: 100 };
const width = 1000 - margin.left - margin.right;
const height = 500 - margin.top - margin.bottom;

// Clear existing elements
d3.select(container).html("");

// Create SVG container
const svg = d3.select(container)
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);

// Tooltip
const tooltip = d3.select(container).append("div")
.attr("class", "tooltip")
.style("opacity", 0)
.style("position", "absolute")
.style("background", "rgba(0, 0, 0, 0.8)")
.style("color", "white")
.style("padding", "10px")
.style("border-radius", "8px")
.style("pointer-events", "none");

// Dropdown for metric selection
const selectorContainer = d3.select(container).append("div")
.style("text-align", "center")
.style("margin", "20px");

selectorContainer.append("label")
.attr("for", "metric-selector")
.text("Select Metric: ")
.style("font-size", "18px")
.style("margin-right", "10px");

const metricSelector = selectorContainer.append("select")
.attr("id", "metric-selector")
.style("font-size", "16px");

metricSelector.selectAll("option")
.data(["Mean", "Median"])
.enter()
.append("option")
.text(d => d)
.attr("value", d => d.toLowerCase());

// Slider container
const sliderContainer = d3.select(container).append("div")
.attr("class", "slider-container")
.style("text-align", "center")
.style("margin", "30px");

// Slider
const yearSlider = sliderContainer.append("input")
.attr("type", "range")
.attr("min", 2010)
.attr("max", 2016)
.attr("step", 1)
.attr("value", 2010)
.attr("id", "year-slider")
.style("width", "600px");

// Year display
const yearDisplay = sliderContainer.append("p")
.attr("id", "year-display")
.style("font-size", "22px")
.style("margin", "10px")
.style("font-weight", "bold")
.style("color", "#007BFF")
.text("Year: 2010");

// Play/Pause button
const playButton = sliderContainer.append("button")
.text("Play")
.attr("id", "play-button")
.style("margin", "10px")
.style("padding", "10px 20px")
.style("font-size", "18px")
.style("cursor", "pointer")
.style("border", "none")
.style("border-radius", "8px")
.style("background", "#28A745")
.style("color", "white");

let isPlaying = false;
let interval;

FileAttachment("cleaned_kickstarter.json").json().then(data => {
function calculateMedian(values) {
values.sort(d3.ascending);
const mid = Math.floor(values.length / 2);
return values.length % 2 === 0 ? (values[mid - 1] + values[mid]) / 2 : values[mid];
}

const groupedData = d3.rollup(
data,
v => ({
meanGoal: d3.mean(v, d => d.meangoal),
medianGoal: calculateMedian(v.map(d => d.meangoal)),
meanAmount: d3.mean(v, d => d.meanamt),
medianAmount: calculateMedian(v.map(d => d.meanamt))
}),
d => Math.round(d.meanyear)
);

const processedData = Array.from(groupedData, ([year, values]) => ({
year,
meanGoal: values.meanGoal,
medianGoal: values.medianGoal,
meanAmount: values.meanAmount,
medianAmount: values.medianAmount
})).sort((a, b) => a.year - b.year);

const x = d3.scaleLinear().domain([2010, 2016]).range([0, width]);
const y = d3.scaleLinear()
.domain([0, d3.max(processedData, d => Math.max(d.meanGoal, d.medianGoal, d.meanAmount, d.medianAmount))])
.range([height, 0]);

svg.append("g")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(x).ticks(7).tickFormat(d3.format("d")));

svg.append("g")
.call(d3.axisLeft(y));

// AXIS LABELS
svg.append("text")
.attr("text-anchor", "middle")
.attr("x", width / 2)
.attr("y", height + 50)
.style("font-size", "16px")
.style("font-weight", "bold")
.text("Year");

svg.append("text")
.attr("text-anchor", "middle")
.attr("transform", `rotate(-90)`)
.attr("x", -height / 2)
.attr("y", -60)
.style("font-size", "16px")
.style("font-weight", "bold")
.text("Amount in USD");

function updateChart(selectedYear, metric) {
yearDisplay.text(`Year: ${selectedYear}`);
const filteredData = processedData.filter(d => d.year <= selectedYear);
const keyGoal = metric === "mean" ? "meanGoal" : "medianGoal";
const keyAmount = metric === "mean" ? "meanAmount" : "medianAmount";

svg.selectAll(".goal-line, .amount-line, .dot").remove();

const lineGoal = d3.line()
.x(d => x(d.year))
.y(d => y(d[keyGoal]));

const lineAmount = d3.line()
.x(d => x(d.year))
.y(d => y(d[keyAmount]));

svg.append("path")
.datum(filteredData)
.attr("class", "goal-line")
.attr("fill", "none")
.attr("stroke", "#007BFF")
.attr("stroke-width", 3)
.attr("d", lineGoal);

svg.append("path")
.datum(filteredData)
.attr("class", "amount-line")
.attr("fill", "none")
.attr("stroke", "#28A745")
.attr("stroke-width", 3)
.attr("d", lineAmount);

svg.selectAll(".dot.goal")
.data(filteredData)
.enter().append("circle")
.attr("class", "dot goal")
.attr("cx", d => x(d.year))
.attr("cy", d => y(d[keyGoal]))
.attr("r", 5)
.attr("fill", "#007BFF")
.on("mouseover", (event, d) => {
tooltip.transition().duration(200).style("opacity", 1);
tooltip.html(`Year: ${d.year}<br>${metric} Goal: $${Math.round(d[keyGoal]).toLocaleString()}`)
.style("left", `${event.pageX + 10}px`)
.style("top", `${event.pageY - 40}px`);
})
.on("mouseout", () => tooltip.transition().duration(300).style("opacity", 0));

svg.selectAll(".dot.amount")
.data(filteredData)
.enter().append("circle")
.attr("class", "dot amount")
.attr("cx", d => x(d.year))
.attr("cy", d => y(d[keyAmount]))
.attr("r", 5)
.attr("fill", "#28A745")
.on("mouseover", (event, d) => {
tooltip.transition().duration(200).style("opacity", 1);
tooltip.html(`Year: ${d.year}<br>${metric} Amount Raised: $${Math.round(d[keyAmount]).toLocaleString()}`)
.style("left", `${event.pageX + 10}px`)
.style("top", `${event.pageY - 40}px`);
})
.on("mouseout", () => tooltip.transition().duration(300).style("opacity", 0));
}

playButton.on("click", () => {
if (isPlaying) {
clearInterval(interval);
playButton.text("Play").style("background", "#28A745");
isPlaying = false;
} else {
interval = setInterval(() => {
let currentYear = +yearSlider.node().value;
yearSlider.node().value = currentYear < 2016 ? ++currentYear : 2010;
updateChart(currentYear, metricSelector.property("value"));
}, 1000);
playButton.text("Pause").style("background", "#DC3545");
isPlaying = true;
}
});

yearSlider.on("input", function () {
updateChart(+this.value, metricSelector.property("value"));
});

metricSelector.on("change", function () {
updateChart(+yearSlider.node().value, this.value);
});

updateChart(2010, "mean");
});

return container;
}

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