viewof chart1 = {
const width = 928;
const height = width;
const margin = 1;
const filteredData = data
.filter(d => d.iso_code && !isNaN(d.co2) && !isNaN(d.population) && d.co2 > 0 && d.population > 0)
.map(d => ({
country: d.country,
year: d.year,
co2: +d.co2,
population: +d.population,
iso_code: d.iso_code,
co2PerCapita: +d.co2 / +d.population
}));
console.log("Datos procesados:", filteredData);
const container = d3.create("div");
const co2Button = document.createElement("button");
co2Button.textContent = "CO₂ Total";
co2Button.style.marginRight = "10px";
co2Button.style.borderRadius = "20px";
co2Button.style.backgroundColor = "#4CAF50";
co2Button.style.color = "white";
const co2PerCapitaButton = document.createElement("button");
co2PerCapitaButton.textContent = "CO₂ Per Cápita";
co2PerCapitaButton.style.marginRight = "10px";
co2PerCapitaButton.style.borderRadius = "20px";
co2PerCapitaButton.style.backgroundColor = "#2196F3";
co2PerCapitaButton.style.color = "white";
// Crear el slider de tiempo
const uniqueYears = Array.from(new Set(filteredData.map(d => d.year))).sort((a, b) => a - b);
const yearSlider = document.createElement("input");
yearSlider.type = "range";
yearSlider.min = 0;
yearSlider.max = uniqueYears.length - 1;
yearSlider.value = 0;
yearSlider.style.marginRight = "10px";
yearSlider.style.marginLeft = "20px";
const yearLabel = document.createElement("span");
yearLabel.textContent = uniqueYears[0]; // Año inicial
const playButton = document.createElement("button");
playButton.textContent = "Play";
playButton.style.marginLeft = "20px";
playButton.style.borderRadius = "20px";
playButton.style.backgroundColor = "#f44336";
playButton.style.color = "white";
// Crear título del gráfico
const chartTitle = document.createElement("h3");
chartTitle.textContent = `Distribución de CO₂ Total (toneladas) por País (Año: ${uniqueYears[0]})`;
chartTitle.style.textAlign = "center";
chartTitle.style.marginTop = "20px";
container.append(() => co2Button);
container.append(() => co2PerCapitaButton);
container.append(() => playButton);
container.append(() => yearSlider);
container.append(() => yearLabel);
container.append(() => chartTitle);
// Crear SVG para el gráfico
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [-margin, -margin, width, height])
.attr("style", "max-width: 100%; height: auto; font: 10px sans-serif;")
.attr("text-anchor", "middle");
container.append(() => svg.node());
// Escala de colores
const color = d3.scaleOrdinal(d3.schemeTableau10);
// Función para actualizar el gráfico
function updateChart(selectedYear, variable) {
const dataForSelectedYear = filteredData.filter(
d => d.year === selectedYear && d.population > 0 && d.co2 > 0
);
console.log(`Datos del año ${selectedYear}:`, dataForSelectedYear);
const pack = d3.pack()
.size([width - margin * 2, height - margin * 2])
.padding(3);
const root = pack(d3.hierarchy({ children: dataForSelectedYear })
.sum(d => variable === 'co2PerCapita' ? d[variable] * 1000000 : d[variable]));
svg.selectAll("*").remove();
const node = svg.append("g")
.selectAll()
.data(root.leaves())
.join("g")
.attr("transform", d => `translate(${d.x},${d.y})`);
const label = variable === 'co2PerCapita' ? 'CO₂ Per Cápita' : 'CO₂ Total';
const unit = variable === 'co2PerCapita' ? 'kg' : 'toneladas';
node.append("title")
.text(d => `${d.data.country}\n${label}: ${d3.format(",.0f")(d.value)} ${unit}`);
node.append("circle")
.attr("fill-opacity", 0.7)
.attr("fill", d => color(d.data.country))
.attr("r", d => d.r);
node.append("text")
.attr("clip-path", d => `circle(${d.r})`)
.selectAll("tspan")
.data(d => [d.data.country, `${d3.format(",.0f")(d.value)} ${unit}`])
.join("tspan")
.attr("x", 0)
.attr("y", (d, i) => `${i - 0.5}em`)
.text(d => d);
chartTitle.textContent = `Distribución de ${label} (${unit}) por País (Año: ${selectedYear})`;
}
updateChart(uniqueYears[0], "co2");
let isPlaying = false;
let interval;
function togglePlay() {
if (isPlaying) {
clearInterval(interval);
playButton.textContent = "Play";
} else {
playButton.textContent = "Pause";
interval = setInterval(() => {
let nextValue = +yearSlider.value + 1;
if (nextValue >= uniqueYears.length) nextValue = 0;
yearSlider.value = nextValue;
const selectedYear = uniqueYears[nextValue];
yearLabel.textContent = selectedYear;
updateChart(selectedYear, co2PerCapitaButton.disabled ? 'co2PerCapita' : 'co2');
}, 500);
}
isPlaying = !isPlaying;
}
playButton.addEventListener("click", togglePlay);
yearSlider.addEventListener("input", () => {
const selectedYear = uniqueYears[yearSlider.value];
yearLabel.textContent = selectedYear;
updateChart(selectedYear, co2PerCapitaButton.disabled ? 'co2PerCapita' : 'co2');
});
co2Button.addEventListener("click", () => {
co2Button.disabled = true;
co2PerCapitaButton.disabled = false;
const selectedYear = uniqueYears[yearSlider.value];
updateChart(selectedYear, 'co2');
});
co2PerCapitaButton.addEventListener("click", () => {
co2Button.disabled = false;
co2PerCapitaButton.disabled = true;
const selectedYear = uniqueYears[yearSlider.value];
updateChart(selectedYear, 'co2PerCapita');
});
return container.node();
}