{
const width = 400;
const height = 400;
const div = d3.create("div");
let fruit = "apple";
const form = div.append("form");
const formDiv = form
.selectAll("div")
.data(["apple", "orange"])
.join("div")
.on("click", function () {
fruit = d3.select(this).datum();
updateSVG();
});
formDiv
.append("input")
.attr("type", "radio")
.attr("name", "fruit")
.attr("id", (d) => d)
.attr("checked", (d) => (d === fruit ? "checked" : null));
formDiv
.append("label")
.attr("for", (d) => d)
.text((d) => d);
const svg = div
.append("svg")
.attr("viewBox", [0, 0, width, height])
.attr("width", width);
const updateSVG = function () {
svg.selectAll("*").remove();
svg
.append("g")
.selectAll("rect")
.data(dataset)
.join("rect")
.attr("x", (d, i) => i * (width / dataset.length))
.attr("y", (d) => height - d[fruit] * 4)
.attr("width", width / dataset.length - 1)
.attr("height", (d) => d[fruit] * 4)
.attr("fill", fruit === "apple" ? "red" : "orange");
svg
.append("g")
.selectAll("text")
.data(dataset)
.join("text")
.text((d) => d[fruit])
.attr("x", (d, i) => (i + 0.5) * (width / dataset.length))
.attr("y", (d) => height - d[fruit] * 4)
.attr("dy", -4)
.attr("text-anchor", "middle")
.attr("fill", fruit === "apple" ? "red" : "orange");
};
updateSVG();
return div.node();
}