Skip to content
Snippets Groups Projects
Commit 055819d7 authored by frajuar's avatar frajuar
Browse files

First commit

parent 93252857
No related branches found
No related tags found
No related merge requests found
let paises = [];
let nombresDeVariables = [];
let seleccionAnno="2020";
document.addEventListener('DOMContentLoaded', function () {
d3.csv("./datos/paises.csv").then(function (data) {
nombresDeVariables = Object.keys(data[0]);
dibujaSelector();
data.forEach(function (fila) {
let countryData = [fila.countryName];
Object.keys(fila).forEach(function (key) {
if (key !== "countryName") {
// Convert the value to a number if it's a valid number, otherwise keep it as a string
const value = isNaN(fila[key]) ? fila[key] : parseFloat(fila[key]);
countryData.push(value);
/*console.log(value);*/
}
});
paises.push(countryData);
});
dibujaMapa(seleccionAnno);
});
});
function dibujaSelector(){
nombresDeVariables.pop();
const container = document.getElementById("yearSelectorContainer");
const select = document.createElement("select");
select.id = "yearSelector"; // Asignamos un id para referencia futura
nombresDeVariables.forEach(function(year) {
const option = document.createElement("option");
option.value = year;
option.textContent = year;
select.appendChild(option); // Agregar la opción al select
});
container.appendChild(select);
select.value=seleccionAnno;
// Escuchar cambios en el selector
select.addEventListener("change", function () {
seleccionAnno = select.value; // Actualizar la variable seleccionAnno
/* console.log(seleccionAnno);*/
dibujaMapa(seleccionAnno);
});
}
function dibujaMapa(seleccionAnno) {
/*console.log(paises);*/
anno=parseInt(seleccionAnno);
let datosAnno=[];
for(i=0;i<paises.length;i++){
datosAnno.push(paises[i][anno-1959]);
}/**aqui seleccionamos los valores para los paises y el anno seleccionado para poder tener el maximo y el minimo*/
//console.log(datosAnno);
let min=Math.min(...datosAnno.filter(value => value !== 0)); /* minimo y maximo para poder hacer la escala de colores */
let max=Math.max(...datosAnno);
d3.json("./JsonPaises/world-geo.json").then(function (geojson) {
// Configuración del mapa
var DivMapa = document.getElementById("map");
var width = DivMapa.clientWidth;
var height = DivMapa.clientHeight;
// Eliminamos mapas anteriores
d3.selectAll("#Map").remove();
// Creamos el svg
var svg = d3.select("#map")
.append("svg")
.attr("id", "Map")
.attr("width", width)
.attr("height", height);
// Configuración de la proyección
var projection = d3.geoEquirectangular()
.scale(width/8.5)
.rotate([0, 0])
.center([0, 0])
.translate([width/2,height/2 +15]);
var path = d3.geoPath().projection(projection);
var logScale = d3.scaleLog().domain([min, max]).range([0, 1]);
var colores = d3.scaleSequential(d3.interpolateViridis).domain([ Math.log(min),Math.log(max)]);
geojson.features.forEach(function (feature) {
const countryName = feature.properties.name;
const index = paises.findIndex(p => p[0] === countryName);
//console.log(`Buscando: ${countryName}, Encontrado en índice: ${index}`);
if (index !== -1) {
// Agregar un valor de datosAnno al GeoJSON
feature.properties.value = datosAnno[index];
} else {
feature.properties.value = 0; // Si no se encuentra, asignar 0
}
});
svg.selectAll("path")
.data(geojson.features)
.enter()
.append("path")
.attr("d", path)
.style("fill", function (d) {
const value = d.properties.value;
// console.log(value);
return value === 0 ? "#cce5df" : colores(Math.log(value)); // Colores para países con datos
})
.style("stroke-width", 0.55)
.style("stroke","black")
.on("mouseover",function(event,d){
const centroid = path.centroid(d);
d3.select(this)
.raise()
.style("stroke-width", 0.75)
.attr("transform", `
translate(${centroid[0]}, ${centroid[1]})
scale(1.2)
translate(${-centroid[0]}, ${-centroid[1]})`);
const textElement=svg.append("text")
.attr("id","texto")
.attr("x", centroid[0])
.attr("y", centroid[1] - 10)
.style("fill","black")
.text(`${d.properties.name}: ${d.properties.value ? d.properties.value.toFixed(2) : 'Sin datos'}`)
.style("opacity", 1);
const textBBox = textElement.node().getBBox();
svg.append("rect")
.attr("class", "background-rect")
.attr("id","rectanguloTexto")
.attr("x", textBBox.x -5)
.attr("y", textBBox.y -2)
.attr("width", textBBox.width + 10)
.attr("height", textBBox.height + 4)
.attr("rx", 5)
.attr("ry", 5)
.style("fill", "white")
.style("opacity", 0.2);
textElement.raise();
})
.on("mouseout",function(){
d3.select(this)
.style("stroke-width", 0.55)
.attr("transform", null);
d3.selectAll("#texto").remove();
d3.selectAll("#rectanguloTexto").remove();
})
.on("click",function(event,d){
dibujaGrafico(d.properties.name,paises);
})
var legend = svg.append("g")
.attr("class", "legend")
.attr("transform", "translate(20, 50)");
var legendScale = d3.scaleLog()
.domain([min, max])
.range([0, 300]);
var legendAxis = d3.axisLeft(legendScale)
.ticks(4)
.tickFormat(d3.format(".2f"));
var legendBar = d3.scaleSequential(d3.interpolateViridis)
.domain([ Math.log(min),Math.log(max)]);
legend.append("g")
.attr("class", "axis")
.call(legendAxis)
.selectAll("text")
.attr("transform", "translate(30, 0)") // Desplazar los valores de la leyenda a la derecha
.style("text-anchor", "start"); // Alinear los valores de la leyenda a la derecha;
for (let i = Math.log(min); i <= Math.log(max); i += 0.1) {
legend.append("rect")
.attr("x", 0)
.attr("y", legendScale(Math.exp(i)))
.attr("width", 20)
.attr("height", legendScale(Math.exp(i + 0.1)) - legendScale(Math.exp(i)))
.style("fill", legendBar(i));
}
});
}
function dibujaGrafico(country,paises){
let datosPais=[];
let index;
for(i=0;i<paises.length;i++){
if(paises[i][0]===country){
// console.log(paises[i][0]);
index=i;
//datosPais.push(paises[i]);
}
}
datosPais=paises[index];
console.log(datosPais);
const datos = nombresDeVariables.map((year, i) => ({
Year: parseInt(year),
Valor: typeof datosPais[i + 1] === "number" ? datosPais[i + 1] : null
})).filter(d => d.Valor !== null); // Filtramos valores nulos o no numéricos
const GraficoLineas = document.getElementById("grafico");
const margin = { top: 20, right: 20, bottom: 50, left: 50 };
const width = GraficoLineas.clientWidth - margin.left - margin.right;
const height = GraficoLineas.clientHeight - margin.top - margin.bottom;
// Se elimina el gráfico existente
d3.selectAll("#GraficoLineasSvg").remove();
// Creamos el SVG para el gráfico
const svg = d3.select("#grafico")
.append("svg")
.attr("id", "GraficoLineasSvg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
// Escalas
// Escala X
const xScale = d3.scaleLinear()
.domain(d3.extent(datos, d => d.Year))
.range([0, width]);
// Escala Y
const yScale = d3.scaleLinear()
.domain([d3.min(datos, d => d.Valor) - 0.05, d3.max(datos, d => d.Valor) + 0.05])
.range([height, 0]);
// Línea
const line = d3.line()
.x(d => xScale(d.Year))
.y(d => yScale(d.Valor));
// Ponemos la línea en el gráfico
const path = svg.append("path")
.data([datos])
.attr("class", "line")
.attr("d", line)
.style("fill", "none")
.style("stroke", "black")
.style("stroke-width", 2);
// Animación para la línea
const totalLength = path.node().getTotalLength();
path
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(3000)
.ease(d3.easeLinear)
.attr("stroke-dashoffset", 0);
// Ejes
// Eje X
svg.append("g")
.attr("class", "x axis")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(xScale).tickFormat(d3.format("d")));
svg.append("text")
.attr("text-anchor", "middle")
.attr("transform", `translate(${width / 2},${height + margin.bottom - 10})`)
.text("Años");
// Eje Y
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale));
svg.append("text")
.attr("text-anchor", "middle")
.attr("transform", `rotate(-90) translate(${-height / 2},${-margin.left + 10})`)
.text("Valor");
// Título
svg.append("text")
.attr("x", width / 2)
.attr("y", -8)
.attr("text-anchor", "middle")
.style("font-size", "18px")
.style("font-weight", "bold")
.text(`Evolución de los datos para ${country}`);
}
Source diff could not be displayed: it is too large. Options to address this: view the blob.
/* General */
body {
margin: 0;
height: 100vh; /* Asegura que el cuerpo ocupe toda la altura */
display: flex;
flex-direction: column; /* Disposición vertical */
}
/* Contenedor del mapa */
#map {
flex: 2; /* Ocupa el doble de espacio que #abajo */
width: 100%; /* Asegura que ocupe el ancho completo */
height: 70%; /* Asegura que el mapa ocupe el 70% de la pantalla */
background-color: rgb(207, 207, 207);
}
#yearSelectorContainer {
position: absolute;
top: 20px; /* Adjust for desired distance from the top */
right: 20px; /* Position it on the right side */
background-color: rgba(255, 255, 255, 0.8); /* Optional, adds some transparency */
padding: 10px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
font-family: Arial, sans-serif;
z-index: 1000; /* Ensures it stays above the map */
}
/* Contenedor inferior */
#grafico {
flex: 0.9; /* Ocupa el tercio restante de la pantalla */
width: 100%; /* Asegura que ocupe el ancho completo */
background-color: rgb(207, 207, 207);
}
/* Estilo para los números */
.text-label {
font-size: 10px;
font-weight: bold;
fill: #000000;
pointer-events: none;
}
This diff is collapsed.
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Mapa Mundial</title>
<link rel="stylesheet" href="./css/estilo.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div id="map">
<!-- Add a container for the year selector -->
<div id="yearSelectorContainer">
</div>
</div>
<div id="grafico"></div>
<script src="./Js/script.js"></script>
</body>
</html>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment