我是 d3 的新手,我正在嘗試根據總能耗值為每個美國州著色。當我使用:
d3.selectAll("path")
.attr("fill", "blue");
我可以成功地將顏色更改為藍色,所以我認為我有正確的基礎。但是當我嘗試應用我自己定義的 colorgradient 函式時,它不再起作用。我在網上看到的大多數示例都使用相同的 json 檔案來創建地圖并分配顏色值。但是我有兩個 json 檔案正在處理——一個包含美國州路徑形狀,另一個包含每個州的元資料。這就是我所擁有的:
const data = await d3.json("states.json");
const energy_data = await d3.csv("Energy Census and Economic Data US 2010-2014.csv");
console.log(energy_data);
const states = topojson.feature(data, data.objects.usStates).features
// draw the states
svg.selectAll(".state")
.data(states)
.enter().append("path")
.attr("class", "state")
.attr("d", path);
const min = d3.min(energy_data, d => parseInt(d.TotalC2010));
const max = d3.max(energy_data, d => parseInt(d.TotalC2010));
const colorgradient = d3.scaleSqrt()
.domain([min, max])
.range(["green", "blue"]);
d3.selectAll("path")
.data(energy_data)
.enter()
.attr("fill", d => colorgradient(d.TotalC2010));
有什么建議嗎?
提前致謝!
編輯:我終于讓它作業了,感謝Andrew Reid。
const state_data = await d3.json("states.json");
const energy_data_raw = await d3.csv("Energy Census and Economic Data US 2010-2014.csv");
const energy_data = new Map(energy_data_raw.map(d => [d.StateCodes, d]))
const states = topojson.feature(state_data, state_data.objects.usStates).features
const min = d3.min(energy_data_raw, d => parseInt(d.TotalC2010));
const max = d3.max(energy_data_raw, d => parseInt(d.TotalC2010));
let colorgradient = d3.scaleSqrt()
.domain([min, max])
.range(["green", "blue"]);
svg.selectAll(".state")
.data(states)
.enter()
.append("path")
.attr("class", "state")
.attr("d", path)
.attr("fill", d => colorgradient(energy_data.get(d.properties.STATE_ABBR).TotalC2010))
uj5u.com熱心網友回復:
問題
這段代碼在這里:
d3.selectAll("path")
.data(energy_data)
.enter()
.attr("fill", d => colorgradient(d.TotalC2010));
根本不應該做任何事情。
首先,假設您的地理資料和能源資料具有相同數量的專案,您正在選擇現有路徑 ( d3.selectAll("path"))。
然后,您要為這些現有路徑分配.data(energy_data)與每個現有路徑匹配的新資料 ( ) - 按照它們的索引順序。
接下來,您創建可能是空的輸入選擇。輸入選擇為資料陣列中沒有相應元素(此處通過索引匹配)的每個專案創建一個元素:如果資料陣列中的專案多于元素,則將輸入新元素。否則,您將有一個空的選擇,因為您不需要輸入任何新元素來表示energy_data.
最后你設定一個空的輸入選擇(通常你會使用 .append() 來指定你想要附加的元素型別,否則,輸入選擇只是一個占位符。因為無論如何這是一個空選擇,什么都不是完畢。
可能的解決方案
我正在通過這個解決方案,因為它看起來像你正在嘗試做的,盡管這不是我推薦的。
看起來好像您正在嘗試將新資料分配給現有選擇 - 這是絕對可能的。在這種方法中,您將使用地理資料來繪制要素,然后為每個要素分配一個新資料集并根據此新資料修改要素。
資料陣列順序相同
如果我們的資料在 geojson 和 csv 中的順序相同,那么我們可以簡單地使用:
selection.data(states)
.enter()
.append("path")
.attr("d", path)
.data(energy_data)
.attr("fill", ...)
因為 .data() 默認情況下通過匹配索引將資料陣列中的專案系結到選擇中的元素,所以energy_data只有當兩個資料陣列的排序相同時,每個特征才會更新為正確的資料。這是一個明顯的限制,但可以克服。
資料陣列排序不同
如果陣列的順序不同,我們需要有一種方法將現有特征與新資料集匹配。默認情況下, .data() 方法通過索引將資料分配給現有元素。但是我們可以使用 .data() 的第二個引數使用 key 函式分配唯一識別符號。
對于這種情況,我假設我們兩個標識states,并energy_data在所在d.properties.id。
當我們輸入我們的路徑時,我們不需要 key 函式,沒有資料可以連接到現有元素。
當我們用energy_data資料更新我們的路徑時,我們希望使用一個鍵函式來確保我們用正確的新資料更新每個元素。key 函式首先在每個現有元素的資料上進行評估,然后在新資料陣列中的每個專案上進行評估。如果找到匹配項,則匹配的新資料將替換舊資料。例如:
svg.selectAll("path")
.data(energy_data, function(d) { return d.properties.id; })
.attr("fill",...
這是一個帶有人為資料的快速示例:
顯示代碼片段
let data = [
{ value: 4, properties: {id: "A" }},
{ value: 6, properties: {id: "B" }},
{ value: 2, properties: {id: "C" }}
]
let color = d3.scaleLinear()
.domain([1,6]).range(["red","yellow"]);
let geojson = {
"type":"FeatureCollection",
"features": [
{
"type": "Feature",
"properties": { id: "C"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ 0, 0 ],
[ 100, 0 ],
[ 100,100 ],
[ 0, 100 ],
[ 0, 0 ]
]
]
}
},
{
"type": "Feature",
"properties": { id: "B"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ 100, 0 ],
[ 200, 0 ],
[ 200, 100 ],
[ 100, 100 ],
[ 100, 0 ]
]
]
}
},
{
"type": "Feature",
"properties": { id: "A"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ 200, 0 ],
[ 300, 0 ],
[ 300,100 ],
[ 200, 100 ],
[ 200, 0 ]
]
]
}
}
]
}
let svg = d3.select("body")
.append("svg")
.attr("width", 300);
svg.selectAll("path")
.data(geojson.features)
.enter()
.append("path")
.attr("d", d3.geoPath(null));
svg.selectAll("path") // Note: You can just chain .data() to .attr() omitting this line.
.data(data, d=>d.properties.id)
.attr("fill", d=>color(d.value));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.1.0/d3.min.js"></script>
使用不同的鍵訪問器以不同方式排序的資料陣列
但是,如果識別符號的位置或名稱與以前不同,我們需要更改關鍵功能。
對于這種情況,我假設states識別符號位于 d.properties.id。對于energy_data,我假設識別符號位于 d.id,這是一個更常見的決議 DSV 位置。
As noted, the key function is evaluated for existing element's data and then new data. this means we need a key function that works for both datasets, which means we need a slightly more complicated key function to compare items from both datasets, for example:
.data(energy_data, function(d) {
if(d.properties)
return d.properties.id; // get the key from items in `states`
else
return d.id; // get the key from items in `energy_data`
})
.attr("fill",...
The key function now will be able to have the new datum replace the old ensuring that the correct feature has the correct data.
Assuming all your identifiers match properly (and are strings) you'll have assigned new data to the existing features.
The downside of this approach is you've lost the original data - if you want to do semantic zooming, check different properties of the geographic data, or revisit the data in the geojson, you need to rebind the original data. Selecting the paths takes time as well, and it assumes there are no other paths that might be mistakenly selected.
這是一個快速示例:
顯示代碼片段
let csv = d3.csvParse(d3.select("pre").remove().text());
let color = d3.scaleLinear()
.domain([1,6]).range(["red","yellow"]);
let geojson = {
"type":"FeatureCollection",
"features": [
{
"type": "Feature",
"properties": { id: "C"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ 0, 0 ],
[ 100, 0 ],
[ 100,100 ],
[ 0, 100 ],
[ 0, 0 ]
]
]
}
},
{
"type": "Feature",
"properties": { id: "B"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ 100, 0 ],
[ 200, 0 ],
[ 200, 100 ],
[ 100, 100 ],
[ 100, 0 ]
]
]
}
},
{
"type": "Feature",
"properties": { id: "A"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ 200, 0 ],
[ 300, 0 ],
[ 300,100 ],
[ 200, 100 ],
[ 200, 0 ]
]
]
}
}
]
}
let svg = d3.select("body")
.append("svg")
.attr("width", 300);
svg.selectAll("path")
.data(geojson.features)
.enter()
.append("path")
.attr("d", d3.geoPath(null));
svg.selectAll("path") // Note: You can just chain .data() to the .attr() omitting this line.
.data(csv, d=>d.properties?d.properties.id:d.id)
.attr("fill", d=>color(d.value));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.1.0/d3.min.js"></script>
<pre>id,value
A,4
B,6
C,2</pre>
推薦方法
要加入空間資料和非空間資料,我建議使用 javascript 地圖。這允許您使用共享識別符號在非空間資料中查找值:
let map = new Map(energy_data.map(function(d) { return [d.id, d] }))
我們可以在energy_datanow 中查找任何專案map.get("someIdentifier")
我們可以使用如下:
.attr("fill", d=> colorgradient(map.get(d.properties.id).TotalC2010))
通過這種方式,我們的空間特征保留了它們的空間資料,但我們可以使用通用識別符號和 javascript 地圖輕松訪問非空間資料。
這是一個使用與上述相同的人為 geojson 和 DSV 資料的快速示例:
顯示代碼片段
let csv = d3.csvParse(d3.select("pre").remove().text());
let map = new Map(csv.map(function(d) { return [d.id, d] }))
let color = d3.scaleLinear()
.domain([1,6]).range(["red","yellow"]);
let geojson = {
"type":"FeatureCollection",
"features": [
{
"type": "Feature",
"properties": { id: "C"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ 0, 0 ],
[ 100, 0 ],
[ 100,100 ],
[ 0, 100 ],
[ 0, 0 ]
]
]
}
},
{
"type": "Feature",
"properties": { id: "B"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ 100, 0 ],
[ 200, 0 ],
[ 200, 100 ],
[ 100, 100 ],
[ 100, 0 ]
]
]
}
},
{
"type": "Feature",
"properties": { id: "A"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[ 200, 0 ],
[ 300, 0 ],
[ 300,100 ],
[ 200, 100 ],
[ 200, 0 ]
]
]
}
}
]
}
let svg = d3.select("body")
.append("svg")
.attr("width", 300);
svg.selectAll("path")
.data(geojson.features)
.enter()
.append("path")
.attr("d", d3.geoPath(null))
.attr("fill", d=> color(map.get(d.properties.id).value));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.1.0/d3.min.js"></script>
<pre>id,value
A,4
B,6
C,2</pre>
其他方法
第三種選擇是組合資料陣列 - 遍歷 geojson 并將 energy_data 中包含的值手動添加到每個特征,這樣您就只有一個資料陣列包含繪制可視化和樣式化所需的所有內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/367897.html
標籤:d3.js
上一篇:D3路徑填充給出了奇怪的結果
