JQuery flot pie chart label formatting
I am trying to format the query and legend pie chart labels.
This is what I have created so far:
This is what I am trying to create (I did it using photoshop):
As you can see, I am struggling to include the percentage and values inside the pie (see that the percentage is in bold and the value is missing) and the vertical alignment is centered.
Here's the code:
(function () {
var data = [
{ label: "Sales & Marketing", data: 9545, color: "#62A83B"},
{ label: "Research & Development", data: 16410, color: "#2897CB"},
{ label: "General & Administration", data: 4670, color: "#DEAB34"}
];
$(document).ready(function () {
$.plot($("#expenses-chart"), data, {
series: {
pie: {
show: true
}
},
legend: {
show: true,
labelFormatter: function(label, series) {
var percent= Math.round(series.percent);
var number= series.data[0][1]; //kinda weird, but this is what it takes
return(' <b>'+label+'</b>: '+ percent + '%');
}
}
});
});
})();
Any ideas? Thank!
+3
source to share
1 answer
Your first question depends a lot on markup and CSS. I would put the legend in my own div and style to vertically align it.
<style>
#wrapper {
display: inline-flex;
}
#legend {
margin: auto 5px;
}
#expenses-chart{
float: left;
width: 300px;
height: 300px;
}
.pieLabel{
color: #fff;
}
</style>
<div id="wrapper">
<div id="expenses-chart"></div>
<div id="legend"></div>
</div>
For your labels inside the pie, you need to specify a custom label formatter :
$.plot($("#expenses-chart"), data, {
series: {
pie: {
show: true,
radius: 150,
label: {
show: true,
radius: 0.5, // place in middle of pie slice
formatter: function(label, series){
var percent = Math.round(series.percent);
var number = series.data[0][2]; // this is the y value of the first point
return (' <b>' + percent + '%</b><br/>$' + number); // custom format
}
}
}
},
legend: {
show: true,
container: $("#legend")
}
}
Putting this together, you create (example here ):
+4
source to share