{
const svg = d3.create("svg")
.attr("width", 600)
.attr("height", 600);
const margin = {top: 40, right: 60, bottom: 60, left: 70};
const xWithMargin = d3.scaleLinear()
.domain(x.domain())
.range([margin.left, 600 - margin.right]);
const yWithMargin = d3.scaleLinear()
.domain(y.domain())
.range([600 - margin.bottom, margin.top]);
const color = d3.scaleOrdinal()
.domain(["setosa", "versicolor", "virginica"])
.range(["#4e79a7", "#f28e2c", "#e15759"]);
const areaExtent = d3.extent(irisTransformado, d => d.area_petalo);
const radiusScale = d3.scaleSqrt()
.domain(areaExtent)
.range([2, 10]);
svg.append("g")
.attr("transform", `translate(0,${600 - margin.bottom})`)
.call(d3.axisBottom(xWithMargin).tickPadding(10))
.attr("font-size", "12px")
.append("text")
.attr("x", 600 - margin.right)
.attr("y", -15)
.attr("fill", "black")
.attr("text-anchor", "end")
.attr("font-size", "16px")
.text("Longitud de Sépalo");
svg.append("g")
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(yWithMargin).tickPadding(10))
.attr("font-size", "12px")
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 15)
.attr("x", -margin.top)
.attr("dy", ".71em")
.attr("fill", "black")
.attr("text-anchor", "end")
.attr("font-size", "16px")
.text("Longitud de Pétalo");
// 3. Añadir puntos con tamaño proporcional al área del pétalo
svg.append("g")
.selectAll("circle")
.data(irisTransformado)
.join("circle")
.attr("cx", d => xWithMargin(d.longitud_sepalo))
.attr("cy", d => yWithMargin(d.longitud_petalo))
.attr("r", d => radiusScale(d.area_petalo)) // El radio ahora depende del área del pétalo
.attr("fill", d => color(d.especie)) // El color sigue dependiendo de la especie
.attr("stroke", "white")
.attr("stroke-width", 1)
.attr("opacity", 0.8);
// 4. Añadir leyenda con texto pequeño
const legend = svg.append("g")
.attr("transform", `translate(${600 - margin.right - 100}, 440)`);
// Añadir título de leyenda
legend.append("text")
.attr("x", 0)
.attr("y", -10)
.attr("font-size", "12px")
.attr("font-weight", "bold")
.text("Especies");
const species = [...new Set(irisTransformado.map(d => d.especie))];
species.forEach((s, i) => {
const legendRow = legend.append("g")
.attr("transform", `translate(0, ${i * 20})`);
legendRow.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", 5)
.attr("fill", color(s));
legendRow.append("text")
.attr("x", 12)
.attr("y", 4)
.attr("font-size", "10px")
.text(s);
});
// Retornamos el canvas.
return svg.node();
}