我正在尝试使用JSON文件创建两个图表
HTML:
<div id="chart-0" class="chart-box"></div>
<div id="chart-1" class="chart-box"></div>
JS:
$(function() {
Highcharts.setOptions({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
dataLabels: {
enabled: true,
format: '<b>{point.name}</b> <br>({point.percentage:.1f} %)'
}
}
}
});
$.getJSON('https://api.myjson.com/bins/16jm21', function(data) {
$.each(data, function(key, val) {
var options = {
chart: {
renderTo: 'chart-' + key
},
title: {
text: val.name
},
series: [{
name: val.series.name,
innerSize: '60%',
data: [val.series.data]
}]
}
console.log(val.series.data)
var chart = new Highcharts.Chart(options);
});
});
});
JSON:
[{"name":"Projeto 1","series":{"name":"Status","innerSize":"60%","data":[{"name":"Andamento","y":"60","color":"#DDDF00"},{"name":"Concluído","y":"19.2","color":"#3498DB"},{"name":"Atrasado","y":"10.8"},{"name":"Outro","y":"6.5"},{"name":"Outro 2","y":"3.5"}]}},{"name":"Projeto 2","series":{"name":"Status 2","innerSize":"60%","data":[{"name":"Andamento","y":"60","color":"#DDDF00"},{"name":"Concluído","y":"19.2","color":"#3498DB"},{"name":"Atrasado","y":"10.8"},{"name":"Outro","y":"6.5"},{"name":"Outro 2","y":"3.5"}]}}]
此json文件包含两个图表的数据。在我尝试通过将val.series.data
传递到options.series.data
来推送数据之前,一切似乎都运行良好。图表加载但是它被打破了,好像它没有正确推送val.series.data
,它不会在控制台中引发任何错误。我不知道我做错了什么,但看起来我错过了很简单的东西。
一些帮助将不胜感激。
这是jsfiddle:https://jsfiddle.net/9bor1od3/
答案 0 :(得分:1)
您的示例代码中存在两个问题。
设置series.data
时,如果它已经是数组,则将其包装在数组中。来自:
data: [val.series.data]
要:
data: val.series.data
series.data
检索到的getJSON
会返回y
值的字符串。你可以修改来源:
{"name":"Outro","y":"6.5"}
要:
{"name":"Outro","y": 6.5}
或parseFloat
结果。一个parseFloat
示例:
$.each(val.series.data, function(k, v) {
val.series.data[k].y = parseFloat(val.series.data[k].y);
});
查看显示的图表的this JSFiddle demonstration。