Leandro Faria
Leandro Faria

Reputation: 445

jQuery flot pie chart label formatting

I'm trying to format my query flot pie chart labels and legend.

This is what I've created so far:

enter image description here

This is what I'm trying to create (I did it using photoshop):

enter image description here

As you can see, I'm struggling to include percentage and values within the pie (see that percentage is bold and the value is not), and vertical-center align the legend.

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('&nbsp;<b>'+label+'</b>:&nbsp;'+ percent + '%');
                }
             }
        });
    });

})();

Any ideas? Thanks!

Upvotes: 3

Views: 9277

Answers (1)

Mark
Mark

Reputation: 108567

Your first question is largely a matter of mark-up and CSS. I would place the legend in it's own div and style that 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 formatter for the labels:

$.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 ('&nbsp;<b>' + percent + '%</b><br/>$' + number); // custom format
        }
      }
    }
  },
  legend: {
    show: true,
    container: $("#legend")
  }
}

Putting this together produces (example here):

enter image description here

Upvotes: 5

Related Questions