我有一個 SVG 十六進制地圖,我使用 foreach 函式加入了我的資料集。
資料集:
var data = [
{ "id": "Scotland ", "value": 5000 },
{ "id": "Wales ", "value": 3000 },
{ "id": "Ireland ", "value": 750 },
{ "id": "North West ", "value": 1250 },
{ "id": "North East ", "value": 4500 },
{ "id": "East Midlands ", "value": 2000 },
{ "id": "South East ", "value": 350 },
{ "id": "South West ", "value": 6000 },
{ "id": "East of England ", "value": 4000 },
{ "id": "West Midlands ", "value": 2500 },
{ "id": "Northern Ireland ", "value": 1000},
{ "id": "Isle of Man ", "value": 3000 },
{ "id": "Yorkshire and the Humber ", "value": 1500 },
{ "id": "Greater London ", "value": 5000 }
];
SVG 樣本:
<g role="menuitem" aria-label="South East " transform="translate(445.5384524232801,-18.74937119481314)" cursor="pointer">
<path cs="100,100" d="M5.5,3.5 L0.5,6.5 L-4.5,3.5 L-4.5,-2.5 L0.5,-5.5 L5.5,-2.5 Z" fill="#ffffff" stroke="#ffffff" fill-opacity="1" stroke-width="0.01" stroke-opacity="1" transform="translate(0,0) scale(1)" class="amcharts-map-image"></path>
</g>
<g role="menuitem" aria-label="South East " transform="translate(409.5336486154187,-18.74937119481314)" cursor="pointer">
<path cs="100,100" d="M5.5,3.5 L0.5,6.5 L-4.5,3.5 L-4.5,-2.5 L0.5,-5.5 L5.5,-2.5 Z" fill="#ffffff" stroke="#ffffff" fill-opacity="1" stroke-width="0.01" stroke-opacity="1" transform="translate(0,0) scale(1)" class="amcharts-map-image"></path>
</g>
<g role="menuitem" aria-label="Greater London " transform="translate(457.534160443724,22.32951986709005)">
<path cs="100,100" d="M5.5,3.5 L0.5,6.5 L-4.5,3.5 L-4.5,-2.5 L0.5,-5.5 L5.5,-2.5 Z" fill="#ffffff" stroke="#ffffff" fill-opacity="1" stroke-width="0.01" stroke-opacity="1" transform="translate(0,0) scale(1)" class="amcharts-map-image"></path>
</g>
該函式遍歷我的資料集并將 ID 映射到 SVG 中的相應 ID。SVG 中的 ID 包含在 g 的 aria-label 屬性中(例如“Scotland”、“South East”、“Wales”...等
功能
const ids = data.map(d => d.id);
ids.forEach(id =>
d3.selectAll(`g[aria-label="${id}"]`)
我的資料包含針對每個 ID/區域的值。我想要做的是使用這樣的色標:
var colorScale = d3
.scaleLinear()
.domain(d3.extent(data, (d) => d.value))
.range(["#5C4D87", "#EC4E6B"])
.interpolate(d3.interpolateHcl)
...并根據分配給區域的值將該顏色應用于我的 SVG。
這是我迄今為止嘗試過的:
const svgUrl = "https://raw.githubusercontent.com/gangrel11/samplefiles/main/amCharts.pixelMap.svg";
d3.xml(svgUrl).then(render);
function render(svg) {
d3.select("body").node().append(svg.documentElement)
const ids = data.map(d => d.id);
ids.forEach(id =>
d3.selectAll(`g[aria-label="${id}"]`)
.select('path')
.style("fill", function(d) {
return colorScale(d)
})
);
uj5u.com熱心網友回復:
迭代您的初始資料而不是 id 映射。
data.forEach(d => {
d3.selectAll(`g[aria-label="${d.id}"]`)
.selectAll('path')
.style("fill",colorScale(d.value))
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/471080.html
標籤:d3.js
