gpt4 book ai didi

javascript - 具有一个对象键/值的 d3 饼图

转载 作者:行者123 更新时间:2023-11-29 10:30:29 24 4
gpt4 key购买 nike

您好,我是 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… }

我的代码很长并且在多个文件中,所以我认为链接它不相关。

我成功地加载了一个带有简单数组的饼图,但我不知道如何访问此处的值。

最佳答案

D3 data 方法接受 3 个东西:

  1. 一个数组;
  2. 一个函数;
  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>

关于javascript - 具有一个对象键/值的 d3 饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47296809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com