D3で描画する image に id を付与できる
その id に対して jquery で操作することにより、D3で描画したマップの外からも要素を操作できる
以下の例ではボタンを押すとマップ中のひとつの要素を非表示にしている
コード例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 Scatter Plot</title>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
<div>
<button id="map-pin-1-button">map-pin-1</button>
</div>
<script>
// 1. データの準備
var dataset = [
[5, 20],
[480, 90],
[250, 50],
[100, 33],
[330, 95],
[410, 12],
[475, 44],
[25, 67],
[85, 21],
[220, 88]
];
var width = 500; // グラフの幅
var height = 500; // グラフの高さ
var margin = { "top": 30, "bottom": 60, "right": 30, "left": 60 };
// 2. SVG領域の設定
var svg = d3.select("body").append("svg").attr("width", width).attr("height", height);
// 3. 軸スケールの設定
var xScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function (d) { return d[0]; })])
.range([margin.left, width - margin.right]);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function (d) { return d[1]; })])
.range([height - margin.bottom, margin.top]);
// 4. 軸の表示
var axisx = d3.axisBottom(xScale).ticks(5);
var axisy = d3.axisLeft(yScale).ticks(5);
svg.append("g")
.attr("transform", "translate(" + 0 + "," + (height - margin.bottom) + ")")
.call(axisx)
.append("text")
.attr("fill", "black")
.attr("x", (width - margin.left - margin.right) / 2 + margin.left)
.attr("y", 35)
.attr("text-anchor", "middle")
.attr("font-size", "10pt")
.attr("font-weight", "bold")
.text("横軸");
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + 0 + ")")
.call(axisy)
.append("text")
.attr("fill", "black")
.attr("x", -(height - margin.top - margin.bottom) / 2 - margin.top)
.attr("y", -35)
.attr("transform", "rotate(-90)")
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.attr("font-size", "10pt")
.text("縦軸");
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + 0 + ")")
.call(axisy)
.append("text")
.attr("fill", "black")
.attr("x", -(height - margin.top - margin.bottom) / 2 - margin.top)
.attr("y", -75)
.attr("transform", "rotate(-90)")
svg.append("g")
.selectAll("circle")
.data(dataset)
.enter()
.append("image")
.attr("xlink:href", "https://github.com/favicon.ico")
.attr("x", function (d) { return xScale(d[0]); })
.attr("y", function (d) { return yScale(d[1]); })
.attr("id", function (d, i) { return "map-pin" + i; })
.on("mouseover", function (e) {
console.log("Mousover")
}).on("click", function (e) {
console.log("Click");
});
</script>
<script>
$('#map-pin-1-button').click(function () {
console.log("Click")
$('#map-pin1').css('display', 'none');
});
</script>
</body>
</html>
参考
https://blog.goo.ne.jp/dak-ikd/e/bc2a572c1633a226dddbedd2aefd7512
https://wizardace.com/d3-scatterplot/
https://stackoverflow.com/questions/20086884/add-image-inside-a-circle-d3
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。