Search code examples
d3.jsscatter-plotc3.jsc3

How to add labels to c3.js scatter plot graph?


Is it possible to add labels to scatter plot points in c3.js like in this google charts example?


https://google-developers.appspot.com/chart/interactive/docs/gallery/bubblechart#javascript


Solution

  • c3 doesn't support this currently - https://github.com/masayuki0812/c3/issues/481. But you can easily add the functionality - just loop through the chart series and points and add the labels as necessary.

    var labels = [
        ['AA', 'BB', 'CC', 'DD', 'EE', 'FF', 'GG', 'HH'],
        ['ZA', 'ZB', 'ZC', 'ZD', 'ZE', 'ZF', 'ZG', 'ZH']
    ];
    // series
    var series = chart.internal.main
                    .selectAll('.' + c3.chart.internal.fn.CLASS.circles)[0];
    // text layers
    var texts = chart.internal.main
                    .selectAll('.' + c3.chart.internal.fn.CLASS.chartTexts)
                    .selectAll('.' + c3.chart.internal.fn.CLASS.chartText)[0]
    series.forEach(function (series, i) {
        var points = d3.select(series).selectAll('.' + c3.chart.internal.fn.CLASS.circle)[0]
        points.forEach(function (point, j) {
            d3.select(texts[i])
                .append('text')
                .attr('text-anchor', 'middle')
                .attr('dy', '0.3em')
                .attr('x', d3.select(point).attr('cx'))
                .attr('y', d3.select(point).attr('cy'))
                .text(labels[i][j])
        })
    });
    

    Fiddle - http://jsfiddle.net/6phuuans/


    enter image description here