这是我在这里的第一个问题,对不起,如果它不是非常简单。
请参阅此示例图片
总之,我想看看碳水化合物的总数,但也要注意糖的含量。
理想的结果将显示在图例中:
108净碳水化合物
其中43g糖类
在图表上总结了浅红色和深红色(20.7%而不是12.4%和8.3%)。
感谢任何帮助!
这是代码:
function drawChart() {
var dataArray = [
//['Macronutrient', 'Calories from macronutrient'],
['Protein', 530],
['Fat', 1127.7],
['Net Carbs', 260.1],
['Sugars', 173.1]
];
var total = getTotal(dataArray);
// Adding tooltip column
for (var i = 0; i < dataArray.length; i++) {
dataArray[i].push(customTooltip(dataArray[i][0], dataArray[i][1], total));
}
// Changing legend
for (var j = 0; j < dataArray.length; j++) {
if (dataArray[j][0]=="Fat") var nrkcal = 9;
else nrkcal = 4;
dataArray[j][0] = Math.round(dataArray[j][1]/nrkcal) + "g " +
dataArray[j][0]; }
// Column names
dataArray.unshift(['Macronutrient', 'Calories', 'Tooltip']);
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
title: 'Calories breakdown',
width: 640,
height: 345,
colors: ['#a9bef1', '#b7faa0', '#fb8679', '#be6c62'],
pieSliceTextStyle: {
color: 'black'
}
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
function customTooltip(name, value, total) {
return name + '<br/><b>' + value + ' (' + ((value/total) * 100).toFixed(1) + '%)</b>';
}
function getTotal(dataArray) {
var total = 0;
for (var i = 0; i < dataArray.length; i++) {
total += dataArray[i][1];
}
return total;
}
我已经做了第一部分,在传奇中展示了什么。唯一剩下的任务是在饼图中将红色切片加在一起 - 而不是12.4和8.3,显示为20.7%。有可能吗?
这是更新后的代码:
// Adding tooltip column
var tc_prc = 0; //Total carbs procent
for (var i = 0; i < dataArray.length; i++) {
if (dataArray[i][0]=="Net Carbs") tc_prc += (dataArray[i][1]/total) * 100;
if (dataArray[i][0]=="Sugars") tc_prc += (dataArray[i][1]/total) * 100;
dataArray[i].push(customTooltip(dataArray[i][0], dataArray[i][1], total));
}
tc_prc = tc_prc.toFixed(1);
// Changing legend
var totalc = 0;
for (var j = 0; j < dataArray.length; j++) {
if (dataArray[j][0]=="Fat") var nrkcal = 9;
else nrkcal = 4;
if (dataArray[j][0]=="Net Carbs") totalc += Math.round(dataArray[j][1]/nrkcal);
if (dataArray[j][0]=="Sugars") totalc += Math.round(dataArray[j][1]/nrkcal);
dataArray[j][0] = Math.round(dataArray[j][1]/nrkcal) + "g " + dataArray[j][0];
}
//Total number of net carbs and sugar
dataArray[2][0] = totalc + 'g Net Carbs';
dataArray[3][0] = 'of which ' + dataArray[3][0];