0
我有4個JavaScript對象,我需要在D3中循環。我需要爲每個對象顯示一張圖。該JSON看起來是這樣的:如何循環訪問D3中的JavaScript對象?
[
{
"name": "Sample 1",
"embed": 10,
"interactive": 10,
"rapidDev": 7,
"support": 7,
"predictive": 4,
"modelDev": 3,
"cost": 2
},
{
"name": "Sample 2",
"embed": 7,
"interactive": 6,
"rapidDev": 7,
"support": 7,
"predictive": 4,
"modelDev": 3,
"cost": 10
},
{
"name": "Sample 3",
"embed": 10,
"interactive": 10,
"rapidDev": 2,
"support": 2,
"predictive": 2,
"modelDev": 2,
"cost": 10
},
{
"name": "Sample 4",
"embed": 2,
"interactive": 7,
"rapidDev": 7,
"support": 7,
"predictive": 10,
"modelDev": 3,
"cost": 8
}
]
每一個「名」是一個軟件標題的名稱,而對方關鍵是數字評級。我需要顯示每個標題的評分,如下所示:
我的代碼當前生成4個SVG,並且每個SVG都有一個標題在上面,但然後我難住了。如果我能得到每個評分的弧線,那麼我可以從那裏拿走它。我只是無法讓弧線出現在SVG中。在「var svg」代碼之後,有人可以用下面的代碼來幫助我,並讓我知道我做錯了什麼?
d3.json("js/tools.json", function(error, data) {
var tau = Math.PI *1.5,
width = "250",
height = "250",
innerRadius = 100,
outerRadius = 120,
i;
var color = d3.scaleOrdinal()
.range(["#eec947", "#9b7560", "#76b7b1", "#f28e2c", "#fe9da6", "#bab1ac"]);
var arc = d3.arc()
.innerRadius(innerRadius-i)
.outerRadius(outerRadius-i)
.startAngle(0);
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "name"; }));
data.forEach(function(d, index) {
d.ratings = color.domain().map(function(name) {
return {name: name, rating: +d[name]};
});
var i = (outerRadius - innerRadius)*(index + 1) + index*3;
var heading = d3.select(".toolCharts").append("h4").text(d.name);
var svg = d3.select("body").selectAll(".toolCharts")
.data(data)
.append("svg")
.attr("class", "chart")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")");
var g = svg.selectAll('.arc')
.data(function(d){return arc(d.ratings);})
.enter()
.append("g");
var background = g.append("path")
.datum({endAngle: tau})
.classed("bg", true)
.style("fill", "#ddd")
.attr("d", arc);
var foreground = g.append("path")
.data(function(d){ return d.rating/10 * tau})
.classed("arc", true)
.style("fill", function(d) {return color(i); })
.attr("d", arc);
var label = g.append("text")
.attr("x", -10)
.attr("y", -outerRadius + i + 20)
.style("text-anchor", "end")
.text(d.ratings.name);
});
});
這裏是你的代碼的OP色標:https://bl.ocks.org/anonymous/f46119c8123d2bec11023dd2f2d0f77e –
我居然沒如果沒有提供域,就知道域默認爲索引。在我提供的答案評論中學習新東西非常酷! – Beemyfriend
這非常有幫助。謝謝! –