Public
Edited
Aug 6, 2024
1 fork
Insert cell
Insert cell
res = fetch('https://d109f9uztt08nv.cloudfront.net/deficit-cero/datos-deficit-cero/graficos/nuevos_hogares_v13.json')
Insert cell
nuevos_hogares = res.json()
Insert cell
regiones_opciones = [...new Set(nuevos_hogares.map(data => data.Región))]
Insert cell
comunas_opciones = [...new Set(dataRegion.map(data => data["Nombre Comuna"]))]
Insert cell
viewof filter_region = select({
title: "Región",
value: "Nacional",
options: regiones_opciones,
selectStyle: {
background: "#EDEDED"
}
})
Insert cell
viewof filter_comuna = select({
title: "Comuna",
value: "Metropolitana",
options: comunas_opciones,
selectStyle: {
background: "#EDEDED"
}
})
Insert cell
dataRegion = nuevos_hogares.filter(data => (data.Región === filter_region))
Insert cell
dataFiltrada = dataRegion.filter(data => (data["Nombre Comuna"] === filter_comuna))
Insert cell
selectDiv = () => {
return html`
<div class="grid-container-select">
<div class="item5">${viewof filter_region}</div>
<div class="item3">${viewof filter_comuna}</div>
</div>
`
}
Insert cell
function graph(data) {
return Plot.plot({
width: 1200, // Ancho del gráfico
height: 500, // Alto del gráfico
marginLeft: 50, // Márgen izquierdo para asegurar que los números del eje Y no se corten
x: {
tickFormat: d3.format(".0f"), // Formato personalizado para el eje X
label: "Año", // Etiqueta del eje X
},
y: {
grid: true,
tickFormat: d => d3.format(",.0f")(d).replace(/,/g, "."), // Formato para el eje Y
label: "Nuevo hogares", // Etiqueta del eje Y
},
color: { legend: true },
marks: [
Plot.ruleY([0]),
Plot.lineY(data, { x: "Año", y: "Migración", stroke: "#31EC9", tip: true }),
Plot.lineY(data, { x: "Año", y: "Crecimiento natural", stroke: "#E053C3", tip: true }),
Plot.lineY(data, { x: "Año", y: "Neto", stroke: "#081575", tip: true }),
]
});
}
Insert cell
Insert cell
viewof grafico = graph(dataFiltrada)
Insert cell
variablesY = ["Migración", 'Crecimiento natural', 'Neto']
Insert cell
coloresY = ["#31E0C9", "#E053C3", "#081575"]
Insert cell
variableX = 'Año'
Insert cell
viewof grafico2 = graph2(dataFiltrada)
Insert cell
function graph2(data) {
const marks = [
Plot.ruleY([0]), // Línea de referencia en y=0
];

// Iterar sobre cada variable en la lista variablesY
variablesY.forEach((variableY, index) => {
const color = coloresY[index % coloresY.length]; // Selecciona un color de la lista de colores
marks.push(
Plot.lineY(data, { x: variableX, y: variableY, stroke: color, tip: true })
);
});

// Definir el tamaño del contenedor
const containerWidth = 900; // Ancho del contenedor
const containerHeight = 650; // Alto del contenedor
// Crear el gráfico y la leyenda como elementos HTML
const container = document.createElement("div");
container.style.position = "relative"; // Establecer posición relativa para posicionar elementos hijos
container.style.width = containerWidth + "px"; // Establecer el ancho del contenedor
container.style.height = containerHeight + "px";
container.style.fontFamily = "'Source Sans Pro', sans-serif"; // Aplica la fuente Source Sans Pro al contenedor

// Crear un contenedor para el filtro y la leyenda con estilo flexbox
const filterAndLegendContainer = document.createElement("div");
filterAndLegendContainer.style.display = "flex";
filterAndLegendContainer.style.alignItems = "center"; // Centrar verticalmente los elementos
filterAndLegendContainer.style.justifyContent = "center"; // Alinear elementos al inicio
filterAndLegendContainer.style.marginBottom = "20px"; // Margen inferior para separación del gráfico

// Agregar el filtro externo
const selectContainer = document.createElement("div");
selectContainer.style.marginRight = "20px"; // Espaciado entre selectDiv() y la leyenda
selectContainer.appendChild(selectDiv());
filterAndLegendContainer.appendChild(selectContainer);

// Crear la leyenda
const legend = d3.select(document.createElement("div"))
.style("display", "flex")
.style("align-items", "center");

variablesY.forEach((variableY, index) => {
const color = coloresY[index % coloresY.length]; // Obtener el color de la lista de colores
const legendItem = legend.append("div")
.style("display", "flex")
.style("align-items", "center")
.style("margin-right", "10px"); // Espacio entre los elementos de la leyenda

legendItem.append("div")
.style("width", "12px")
.style("height", "12px")
.style("background-color", color)
.style("margin-right", "5px");

legendItem.append("span")
.text(variableY);
});

// Agregar la leyenda al contenedor flexbox
filterAndLegendContainer.appendChild(legend.node());

// Agregar el contenedor flexbox al contenedor principal
container.appendChild(filterAndLegendContainer);

// Agregar el gráfico al contenedor principal
container.appendChild(Plot.plot({
width: 850, // Ancho del gráfico
height: 500, // Alto del gráfico
marginLeft: 50,
x: {
label: 'Año', // Etiqueta del eje X
tickFormat: d3.format(".0f") // Formato personalizado para el eje X
},
y: {
label: 'Nuevo hogares', // Etiqueta del eje Y
grid: true,
tickFormat: d => d3.format(",.0f")(d).replace(/,/g, ".") // Formato para el eje Y
},
marks: marks
}));

// Agregar el logo "Powered by Unholster"
const unholsterLogoLink = document.createElement("a");
unholsterLogoLink.setAttribute("href", "https://unholster.com");
unholsterLogoLink.setAttribute("target", "_blank"); // Abrir enlace en una nueva pestaña
unholsterLogoLink.style.position = "absolute"; // Establecer posición absoluta para el logo
unholsterLogoLink.style.bottom = "40px"; // Posicionar el logo 10px desde el borde inferior
unholsterLogoLink.style.right = "50px"; // Posicionar el logo 10px desde el borde derecho
const unholsterLogo = document.createElement("img");
unholsterLogo.setAttribute("src", "https://d2v5qzywcd0fzd.cloudfront.net/viz-decidechile/30annos/logo-unholster/Powered%20by%20Unholster%202.png");
unholsterLogo.setAttribute("height", "20");
unholsterLogoLink.appendChild(unholsterLogo);
container.appendChild(unholsterLogoLink);

// Agregar el texto en la esquina inferior izquierda
const bottomLeftText = document.createElement("div");
bottomLeftText.innerText = "Fuente: Elaboración propia basado en datos INE-CEPAL"; // Aquí puedes cambiar el texto a lo que necesites
bottomLeftText.style.position = "absolute"; // Establecer posición absoluta para el texto
bottomLeftText.style.bottom = "40px"; // Posicionar el texto 0px desde el borde inferior
bottomLeftText.style.left = "20px"; // Posicionar el texto 50px desde el borde izquierdo
bottomLeftText.style.fontSize = "14px"; // Tamaño de fuente del texto
bottomLeftText.style.color = "#707070"; // Color del texto (puedes cambiarlo según tus necesidades)
bottomLeftText.style.fontFamily = "'Source Sans Pro', sans-serif"; // Aplica la fuente Source Sans Pro

container.appendChild(bottomLeftText); // Agregar el texto al contenedor principal

// Retornar el contenedor que incluye el gráfico y la leyenda
return container;
}


Insert cell

<style>
/* Grid container select */

.item3 {
grid-area: tipomapa;
min-width: 0;
min-height: 0;
}

.item4 {
grid-area: seleccion;
min-width: 0;
min-height: 0;
}

.item5 {
grid-area: genero;
min-width: 0;
min-height: 0;
}

.item6 {
grid-area: ano;
min-width: 0;
min-height: 0;
}

.grid-container-select {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
grid-gap: 0px;
}

</style>

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