如何基于此 JSON 格式在 C3(或 D3)图中显示数据:
[{"Type":"Dog","Number":13},{"Type":"Cat","Number":21}]
这是带有来自 JSON 的数据的 Angular Controller ,问题在于定义 keys
属性。我对将类型与数字合并有点困惑。请看一下 plunker
angular.module('c3example', [])
.controller('ExampleCtrl', function($scope){
d3.json('/chartData.json', function(err, data){
if(err){ throw err; }
$scope.data = data;
$scope.chart_types = c3.generate({
bindto: d3.select('#chart'),
size: {
weight: 640,
height: 480
},
data: {
json: $scope.data,
keys: {
value: ['Dog', 'Cat'],
},
type: 'bar'
},
bar: {
width: {
ratio: 0.5 //
}
}
});
});
})
并在 HTML 中进行绑定(bind):
<!DOCTYPE html>
<html>
<body ng-app="c3example" ng-controller="ExampleCtrl">
<div class="row">
<div id="chart" build-chart></div>
</div>
</body>
</html>
最佳答案
实际上,您的键枚举数组必须与包含值的 JSON 键匹配:
替换:
[{"Type":"Dog","Number":13},{"Type":"Cat","Number":21}]
作者:
[{"Dog":13, "Cat":21}, {"Dog":42, "Cat":31}, ...]
注意:您可以考虑使用小写键以避免错误。
编辑:这是您的 Controller 的外观
angular.module('c3example', [])
.controller('ExampleCtrl', function($http, $scope) {
$http.get('chartData.json') // Use angular $http instead of d3.json to use promise chaining
.then(function ( json ) {
$scope.data = formatData(json.data); // format received data
// generate chart
$scope.chart_types = c3.generate({
bindto: d3.select('#chart'),
size: {
weight: 640,
height: 480
},
data: {
json: $scope.data,
keys: {
value: ['Dog', 'Cat'],
},
type: 'bar'
},
bar: {
width: {
ratio: 0.5
}
}
});
},
function ( err ) {
console.log(err); // log if an error occurs
});
// function that take you raw data into input and return a c3 compatible array
function formatData ( json ) {
var formattedData = [],
object = {};
// fill object with data
angular.forEach(json, function(row) {
if (row.hasOwnProperty('Type') && row.hasOwnProperty('Number')) {
this[row.Type] = row.Number;
}
},object);
formattedData.push(object); // push c3 object in the array
return formattedData;
}
})
关于javascript - 在 C3 (D3) 中显示 JSON 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35381507/