Search code examples
javascriptmorris.js

Morris js Display values in percentage format


I am drawing some charts for a school project pulling data from a mysql database. Here is what I've done so far:

DONUT CHARTS

JS CODE:

Morris.Donut({
    element: 'donut-quanti',
    data: [
    {label: "USE FACEBOOK", value: <?php echo $fb_yes;?> },
    {label: "DON'T USE FACEBOOK", value: <?php echo $fb_no;?>}
    ]
    });

BAR CHARTS

JS CODE:

Morris.Bar({
        element: 'bars-status',
        data: [
        {x:'RARELY',a:<?php echo $fb_rar;?>},
        {x:'EV WEEK.',a:<?php echo $fb_ew;?>},
        {x:'EV DAY',a:<?php echo $fb_ed;?>},
        {x:'MULT. TIMES PER DAY',a:<?php echo $fb_mtd;?>}                   
        ],
        xkey:'x',
        ykeys:'a',
        labels:['TOTAL']
        });

Is there a way to display the numeric values (rapresented by the php variables $fb_*) IN PERCENTAGE FORMAT from javascript code (not echoing variable/total * 100 in php ) ?


Solution

  • For the donut you need to use the formatter parameter

    formatter: function (value, data) { return (value/total *100) + '%'; }
    

    See: http://morrisjs.github.io/morris.js/donuts.html


    For the bar you need to use hover callback

    hoverCallback: function (index, options, content) {
      var row = options.data[index];
      //assumes you have already calculated the total of your own dataset
      return (value/total *100)+'%';
    }
    

    See: http://morrisjs.github.io/morris.js/bars.html