PauloB PauloB - 2 months ago 13
JSON Question

Use only the 5 higher values in amCharts pie?

My data call can have lots of small elements (in percentage) that I would like to ignore, I only need the top 5 in my amCharts pie.

Can this be accomplished with amCharts or I should treat the data before?

please see my [jsfiddle][1]

[1]: http://jsfiddle.net/pbarros/xznxbnc7/3/


thanks

Answer

You can use the hideLabelsPercent property to set a threshold for the lowest allowed percentage you want a label for. If you want to do this dynamically, you can set this in the init event by finding the 5th largest percents value in the chart's chartData array and use it as your hideLabelsPercent threshold. I've updated your handleInit method to do this:

function handleInit(e) {
  if (e.chart.chartData.length > 5) {
    //sort the copy of the chartData array from largest to smallest
    //if your data is pre-sorted, then you can skip this step
    var sortedData = e.chart.chartData.slice().sort(function(lhs, rhs) {
      return rhs.percents - lhs.percents;
    });

    //set the threshold equal to the 5th largest slice's percents value so that the rest are hidden
    e.chart.hideLabelsPercent = sortedData[4].percents;

    //redraw the chart
    e.chart.validateNow();
  }
}

Updated fiddle: http://jsfiddle.net/xznxbnc7/9/

Edit since I misread the question

If you only want to show the top five slices from your dataset, you can filter on your backend or use the init method to sort and modify your dataProvider to contain only the top five.

function handleInit(e) {
  if (e.chart.chartData.length > 5) {
    //sort the copy of the chartData array from largest to smallest
    //if your data is pre-sorted, then you can skip this step
    var sortedData = e.chart.dataProvider.slice().sort(function(lhs, rhs) {
      return rhs[e.chart.valueField] - lhs[e.chart.valueField];
    });

    //only put in the top 5.
    e.chart.dataProvider = sortedData.slice(0, 5);

    // redraw the chart
    e.chart.validateData();
  }
}

Fiddle: http://jsfiddle.net/g3cchyjg/1

Comments