Pruebas D3
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://unpkg.com/d3-simple-slider"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.scatter-container {
margin: auto;
width: 800px;
height: 80000px;
}
.svg-plot, .canvas-plot {
position: absolute;
}
.legend {
font-size: 12px;
}
rect {
stroke-width: 2;
}
</style>
</head>
<body>
<h1>Gapminder Data</h1>
<div class="slider-container"></div>
<div class="year-container"></div>
<div class="scatter-container"></div>
<div class="legend"></div>
<script>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://unpkg.com/d3-simple-slider"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.scatter-container {
margin: auto;
width: 800px;
height: 80000px;
}
.svg-plot, .canvas-plot {
position: absolute;
}
.legend {
font-size: 12px;
}
rect {
stroke-width: 2;
}
</style>
</head>
<body>
<h1>Gapminder Data</h1>
<div class="slider-container"></div>
<div class="year-container"></div>
<div class="scatter-container"></div>
<div class="legend"></div>
<script>
//Definición de variables
//Altura y anchura con márgenes
const totalWidth = 800;
const totalHeight = 500;
// Slider y sus textos
var svgSlider = d3.select(".slider-container")
svgSlider.append("p")
.attr("x", 20)
.attr("y", 20)
.attr("text-anchor", "middle")
.style("font-size", "18px")
.attr("font-family", "Verdana")
.attr("font-weight", "bold")
.text("Slider Para la selección del año a visualizar");
// Slider como tal
svgSlider.append("input")
.attr("type", "range")
.attr("min", 1964)
.attr("max", 2013)
.attr("step", "1")
.attr("id", "year")
.on("input", function input() {
updateYear();
update();
});
// Funcion para actualizar el año seleccionado con el slider
function updateYear() {
var slider_year = document.getElementById("year").value;
d3.select(".year-container").attr("x", 20)
.attr("y", 20)
.attr("text-anchor", "middle")
.style("font-size", "18px")
.attr("font-family", "Verdana")
.attr("font-weight", "bold").text(slider_year)
}
// Llamado inicial a las funciones para ver el grafico al abrir
updateYear();
update();
// funcion que pinta el grafico
function update() {
//se obtiene el valor del slider
var slider_year = document.getElementById("year").value;
//console.log(slider_year)
var margin = {
top: 45,
right: 20,
bottom: 50,
left: 81
};
var width = totalWidth - margin.left - margin.right;
var height = totalHeight - margin.top - margin.bottom;
//Defino el asignador de colores por region
var colorAsign = d3.scaleOrdinal(d3.schemeCategory10);
//Propiedades del contenedor del grafico
d3.select(".scatter-container").html("");
var svg = d3.select(".scatter-container")
.append("svg:svg")
.attr("width", totalWidth)
.attr("height", 1500)
.attr('class', 'svg-plot')
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
//Le agrego un titulo
svg.append("text")
.attr("x", (width / 2))
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.style("font-size", "24px")
.style("text-decoration", "underline")
.attr("font-family", "Verdana")
.attr("font-weight", "bold")
.text("Título: Datos de Gapminder para el año Seleccionado");
//Defino el canvas
const canvasChart = d3.select(".scatter-container").append('canvas')
.attr('width', width)
.attr('height', 1500)
.style('margin-left', margin.left + 'px')
.style('margin-top', margin.top + 'px')
.attr('class', 'canvas-plot');
//Contexto del canvas
const context = canvasChart.node().getContext('2d');
//Leo los datos del fichero
d3.csv("gapminder_data.csv").then(datos => {
//console.table(datos)
// se definen los scalers de los ejes x e y
const xExtent = d3.extent(datos, d => d.fertility)
const xScale = d3.scaleLinear()
.domain(xExtent)
.range([0, width])
.nice();
const yMax = d3.max(datos, d => d.life)
const yScale = d3.scaleLinear()
.domain([0, yMax])
.range([height, 0])
.nice();
// se define scaler para el tamaño de los puntos
const popMax = d3.max(datos, d => d.population)
const popMin = d3.min(datos, d => d.population)
const sizeScale = d3.scaleLinear(d3.scaleSqrt())
.domain([popMin, popMax])
.range([3, 100]).clamp(true)
.nice()
const yearMax = d3.max(datos, d => d.year)
const yearMin = d3.min(datos, d => d.year)
var yearScaler = d3.scaleLinear()
.domain([0, yearMax])
.range([0, width])
.clamp(true);
//Se crean los ejes x e y
const xAxis = d3.axisBottom()
.scale(xScale)
//Al eje y se le modifican los ticks
const yAxis = d3.axisLeft()
.tickSizeOuter(10)
.tickSizeInner(2)
.scale(yScale)
//Se agregan los ejes x e y
svg.append('g')
.attr("transform", `translate(0,${height})`)
.call(xAxis)
svg.append('g')
.call(yAxis)
// Título del eje Y con propiedades cambiadas
svg.append('g').append('text')
.attr('x', `-${height/1.4}`)
.attr('dy', '-2.0em')
.attr('transform', 'rotate(-90)')
.attr("font-family", "Verdana")
.attr("font-weight", "bold")
.text('Life Expectancy (Years)');
// Título del eje X con propiedades cambiadas
svg.append('g').append('text')
.attr('x', `${width/2}`)
.attr('y', `${height + 40}`)
.attr("font-family", "Verdana")
.attr("font-weight", "bold")
.text('Fertility');
//Se pintan los puntos solo en el caso que tengamos toda la información necesaria. Esto es debido a que el dataset no siempre tiene todos los campos informados.
datos.forEach(fila => {
//console.log(fila.child_mortality)
if (fila.Year == slider_year && fila.fertility != "" && fila.life != "" && fila.population != "") {
drawPoint(fila);
}
});
// Funcion que pinta un punto en el gráfico
function drawPoint(fila) {
context.beginPath();
//Se pinta un punto según el color de su region
context.fillStyle = colorAsign(fila.region);
const px = xScale(fila.fertility);
const py = yScale(fila.life);
//según la población se define el radio del circulo a pintar mediante un scaler
context.arc(px, py, sizeScale(fila.population / 10), 0, 2 * Math.PI, true);
context.fill();
}
// Agrego leyenda
var legendRectSize = 18;
var legendSpacing = 4;
var legend = svg.selectAll('.legend')
.data(colorAsign.domain())
.enter()
.append('g')
.attr('class', 'legend')
.attr("transform", function(d, i) {
var height = legendRectSize + legendSpacing;
var offset = -550 + height * colorAsign.domain().length / 2;
var horz = -2 * legendRectSize;
var vert = i * height - offset;
return 'translate(' + horz + ',' + vert + ')';
});
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', colorAsign)
.style('stroke', colorAsign);
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.attr("font-family", "Verdana")
.text(function(d) {
return d;
});
});
}
</script>
</body>
</script>
</body>
https://d3js.org/d3.v5.min.js
https://unpkg.com/d3-simple-slider
https://d3js.org/d3.v5.min.js
https://unpkg.com/d3-simple-slider