问题
I need a pie chart and found Flot. It looks simple and powerful, but all of the examples I have found describe the "data" using fixed values (e.g. [1,2]) but I need to show dynamic data. I have five variables that must ultimately add up to 100. I want to include only those that have a value > 0, and if they don't total to 100, I want to add an element that shows the missing percent. The problem is that I don't know how to dynamically construct the data parameter.
My code is below. There are two problems with it: 1) The $.plot does nothing - no error and no grapy 2) I don't know how to add the label text
function updatePieChart() {
var total = 0;
var data = new Array();
var verb = "";
var dataIndex = 0;
for (var dataIndex = 0; dataIndex < 5; dataIndex++) {
var duty = "DUTY_" + (dataIndex + 1);
var d = getData(duty + "_PERCENTAGETIMESPENT");
if (isNumeric(d)) {
d = parseInt(d);
if (d > 0) {
total += d;
data[dataIndex] = new Array();
data[dataIndex].push(d);
verb = getData(duty + "_SKILL");
if (verb == "") verb = duty + dataIndex;
log(duty + dataIndex + ' value: ' + d);
}
}
}
var count = data.length;
if (total != 100) {
if (total < 100) {
var missingDataNum = 100 - total;
data[count] = new Array();
data[count].push(missingDataNum);
verb = '**MISSING**';
log(verb + missingDataNum);
}
}
$.plot($('#pieChart'), data,
{
series: {
pie: {
show: true,
}
},
legend: {
show: false
}
});
}
回答1:
var ary = new Array();
ary.push(1); // this is where you would push the numbers that are supposed to add to 100
ary.push(2);
ary.push(23);
ary.push(40);
ary.push(10);
ary.push(8);
var result = 0;
for (var i = 0; i< ary.length; i++) {
result += ary[i];
}
Now result
should contain the total. Next:
if (result < 100){
var missing = 100 - result;
ary.push(missing);
}
Then I just pushed missing
to the end of the array. So the contents of array will ad up to exactly 100, and the "empty" (in this case 16) is that last element in the graph.
Is that what you were looking for?
EDIT -- I would do the following to prevent the + from getting confused in JS.
if (total != 100) {
if (total < 100) {
var missinDataNum = 100 - total;
series.push('{label: **MISSING**,data: ' + missingDataNum + '}');
}
}
* SECOND EDIT *
if (d1 > 0) series.push('{label: "' + d1v + '",data: ' + d1 + '}');
if (d2 > 0) series.push('{label: "' + d2v + '",data: ' + d2 + '}');
if (d3 > 0) series.push('{label: "' + d3v + '",data: ' + d3 + '}');
if (d4 > 0) series.push('{label: "' + d4v + '",data: ' + d4 + '}');
if (d5 > 0) series.push('{label: "' + d5v + '",data: ' + d5 + '}');
回答2:
Fixed. See What is the format of jQuery Flot data when passing in the data as variables. Problem was that I wasn't formatting the data object as a jSON object correctly.
来源:https://stackoverflow.com/questions/13884325/flot-pie-chart-doesnt-show-revised-code