【问题标题】:d3 Pie chart with one object key /value具有一个对象键/值的 d3 饼图
【发布时间】:2017-11-14 23:11:42
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript d3.js charts


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    • 2018-09-23
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多