简体   繁体   English

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

[英]d3 Pie chart with one object key /value

Hello I am quite new with d3 and javascript. 你好,我对d3和javascript很新。 I am trying to display a pie chart with one object filled with mutiple keys and values. 我试图显示一个饼图,其中一个对象充满了多个键和值。

Here my object : 在这里我的对象:

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… }

My code is quite long and in mutiple files so I don't think it's relevant to link it. 我的代码很长,而且文件很多,所以我认为链接它并不重要。

I succeed to load a pie chart with a simple array but I do not know how to access the values here. 我成功加载了一个带有简单数组的饼图,但我不知道如何访问这里的值。

D3 data method accepts 3 things: D3 data方法接受3件事:

  1. An array; 数组;
  2. A function; 功能;
  3. Nothing; 没有;

Therefore, you have to convert that object in an array of objects, with a specific property for the category and a property for the value. 因此,您必须在对象数组中转换该对象,具有该类别的特定属性和该值的属性。 For instance: 例如:

 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) 

Here is a basic demo with a portion of your object: 这是一个基本演示,其中包含一部分对象:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM