简体   繁体   中英

Rotated bar chart data label format

I am trying to format the data label I have on this rotated x axis bar chart found here: http://jsfiddle.net/blackrimsolutions/01bqmbws/

If I only put:

labels: true

It shows the label but not formatted in percentages.

If I call the labels array:

        labels: {
        format: {
            data1: d3.format('%'),
            data2: d3.format('%'),
            data3: d3.format('%'),
            data4: d3.format('%'),
            data5: d3.format('%'),
            data6: d3.format('%'),
            data7: d3.format('%'),
            data8: d3.format('%'),
            data9: d3.format('%'),
            data10: d3.format('%')
        }
    }

The data labels go away.

I can't have both label: true and the array. I have tried several other ways to get it to work but it mainly seems to not work on rotated axis.

It works on this chart:

var chart1 = c3.generate({
bindto: "#chart1",
padding: {
    top: 20,
    right: 40,
    left: 40
},
data: {
    x: 'x',
    columns: [
        ['x', '2013', '2014'],
        ['data1', 0, 0],
        ['data2', 0, 0]
    ],
    names: {
        data1: 'Sales Growth',
        data2: 'Trans Growth'
    },
    type: 'bar',
    labels: {
        format: {
            data1: d3.format('%'),
            data2: d3.format('%')
        }
    }
},
grid: {
    y: {
        show: true
    }
},
transition: {
    duration: 2000
},
bar: {
    width: {
        ratio: 0.5 
    }
},
axis: {
    y: {
        tick: {
            format: d3.format('%')
        }
    },
    x: {
        type: 'category',
        tick: {
            rotate: 0,
            multiline: false
        },
        centered: true,
        height: 30
    }
},
color: {
    pattern: ['#A2AD00', '#FEB612', '#00A9ED', '#004165', '#F79447', '#C01324', '#FB4F14']
},
tooltip: {
    show: false
}
});

But that's it. Any advice is greatly appreciated.

Thanks!!

I was able to successfully format all of the data sets using the format function built in to C3.js, and with the help of a javascript rounding answer here on Stack .

The format for the function is:

format: function (v, id, i, j) { ... }
  • v is the value of the data point where the label is shown.
  • id is the id of the data where the label is shown.
  • i is the index of the data point where the label is shown.
  • j is the sub index of the data point where the label is shown.

Here is my final labels code:

    labels: {
        format: function (v) {
            'use strict';
            var percent = (Math.round((v * 1000) / 10) / 100);
            return (percent * 100).toFixed(2) + '%';
        }
    }

Thanks everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM