jQuery flot饼图标签格式

时间:2015-01-11 02:07:25

标签: jquery css charts flot pie-chart

我正在尝试格式化我的查询flot饼图标签和图例。

这是我到目前为止所创造的:

enter image description here

这就是我想要创造的东西(我是用photoshop做的):

enter image description here

正如您所看到的,我很难在饼图中包含百分比和值(请参阅百分比为粗体而值不是),垂直居中对齐图例。

以下是代码:

(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 + '%');
                }
             }
        });
    });

})();

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:4)

你的第一个问题主要是标记和CSS。我会将图例放在它自己的div中,并style that to vertically对齐它。

<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>

对于饼图中的标签,您需要为标签指定自定义格式化程序

$.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")
  }
}

将它们放在一起产生(例如here):

enter image description here