[英]How to add Label to each state in d3.js (albersUsa)?
us.json
加載,但是當我嘗試添加Label名稱時,我無法使其工作。 我沒有在.json
文件中看到name屬性,所以如何添加每個州名? 我對這個框架很陌生。
我在Google和Stackoverflow上嘗試了不同的教程,但它們都不適合我。 這是我試過的情侶教程的鏈接,我認為值得。
我擔心的問題:
http://d3js.org/topojson.v1.min.js
? .html
文件(框架已加載)
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
.js
文件:
var width = 1500,
height = 1100,
centered;
var usData = ["json/us.json"];
var usDataText = ["json/us-states.json"];
var projection = d3.geo.albersUsa()
.scale(2000)
.translate([760, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.style("width", "100%")
.style("height", "100%");
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", clicked);
var g = svg.append("g");
d3.json(usData, function(unitedState) {
g.append("g")
.attr("class", "states-bundle")
.selectAll("path")
.data(topojson.feature(unitedState, unitedState.objects.states).features)
.enter()
.append("path")
.attr("d", path)
.attr("class", "states")
.on("click", clicked);
});
先謝謝大家。 如果你告訴我你在哪里學習d3.js我也很感激。
如你所說,你的us.json
中沒有州名。 然而,它擁有獨特的ID,幸運的是,Bostock先生已將這些ID映射到這里 。
所以,讓我們稍微修改一下這段代碼。
首先,使json
請求拉取數據:
// path data
d3.json("us.json", function(unitedState) {
var data = topojson.feature(unitedState, unitedState.objects.states).features;
// our names
d3.tsv("us-state-names.tsv", function(tsv){
// extract just the names and Ids
var names = {};
tsv.forEach(function(d,i){
names[d.id] = d.name;
});
現在添加我們的可視化
// build paths
g.append("g")
.attr("class", "states-bundle")
.selectAll("path")
.data(data)
.enter()
.append("path")
.attr("d", path)
.attr("stroke", "white")
.attr("class", "states");
// add state names
g.append("g")
.attr("class", "states-names")
.selectAll("text")
.data(data)
.enter()
.append("svg:text")
.text(function(d){
return names[d.id];
})
.attr("x", function(d){
return path.centroid(d)[0];
})
.attr("y", function(d){
return path.centroid(d)[1];
})
.attr("text-anchor","middle")
.attr('fill', 'white');
....
這是一個有效的例子 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.