你好,我是d3和javascript的新手。我试图用一个填充多个键和值的对象来显示饼图。
我的目标是:
dataset Object { $Allied Health Professions, Dentistry, Nursing and Pharmacy: 4, $Psychology, Psychiatry and Neuroscience: 4, $Biological Sciences: 4, $General Engineering: 4, $Architecture, Built Environment and Planning: 4, $Geography, Environmental Studies and Archaeology: 4, $Business and Management Studies: 4, $Law: 4, $Social Work and Social Policy: 4, $Education: 4, 5 de plus… }我的代码很长,在多个文件中,所以我不认为链接它是相关的。
我成功地用一个简单的数组加载了一个饼图,但是我不知道如何在这里访问这些值。
发布于 2017-11-14 23:53:24
D3 data方法接受3件事情:
因此,您必须在一个对象数组中转换该对象,其中一个特定属性用于类别,一个属性用于该值。例如:
var obj = {
"Allied Health Professions, Dentistry, Nursing and Pharmacy": 4,
"Psychology, Psychiatry and Neuroscience": 4,
"Biological Sciences": 4,
"General Engineering": 4,
"Architecture, Built Environment and Planning": 4
};
var data = [];
for (var key in obj) {
data.push({
name: key,
value: obj[key]
})
};
console.log(data)
下面是一个包含部分对象的基本演示:
var obj = {
"Allied Health Professions, Dentistry, Nursing and Pharmacy": 4,
"Psychology, Psychiatry and Neuroscience": 4,
"Biological Sciences": 4,
"General Engineering": 4,
"Architecture, Built Environment and Planning": 4
};
var data = [];
for (var key in obj) {
data.push({
name: key,
value: obj[key]
})
};
var arc = d3.arc().outerRadius(100).innerRadius(0);
var pie = d3.pie().value(function(d) {
return d.value
});
var colors = d3.scaleOrdinal(d3.schemeCategory10)
var svg = d3.select("svg")
.append("g")
.attr("transform", "translate(100,100)")
svg.selectAll(null)
.data(pie(data))
.enter()
.append("path")
.attr("d", arc)
.style("fill", function(d, i) {
return colors(i)
})<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="200" height="200"></svg>
https://stackoverflow.com/questions/47296809
复制相似问题