如何在c3.js散点图中添加标签?

时间:2015-07-20 10:24:04

标签: d3.js scatter-plot c3.js c3

是否可以添加标签来散布c3.js中的绘图点,就像在这个谷歌图表示例中一样?

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

2 个答案:

答案 0 :(得分:5)

c3目前不支持此项目 - https://github.com/masayuki0812/c3/issues/481。但您可以轻松添加功能 - 只需遍历图表系列和点,并根据需要添加标签。

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])
    })
});

小提琴 - http://jsfiddle.net/6phuuans/

enter image description here

答案 1 :(得分:0)

目前,C3.js并未向我们提供向散点图中添加标签的选项。但是可以使用以下方法添加响应式数据标签:

  1. 在呈现图表之后(在图表的“onrendered”属性中),识别数据点(标签)并添加从相关圆圈中挑选的x和y坐标的标签,作为标签兄弟。
  2. 代码段:

    onrendered: function(){
      // get the parent of the the <circles> to add <text as siblings>
      var g = d3.selectAll('.c3-circles');
      //Get all circle tags
      var circles = d3.selectAll('circle')[0];
      //go to each circle and add a text label for it
      for(var i = 0; i < circles.length; i++){
        //fetch x-coordinate
        var x = $(circles[i])[0].cx;
        //fetch y-coordinate
        var y = $(circles[i])[0].cy;
    
        //create and append the text tag
        g.append('text')
          .attr('y', y.baseVal.value - 15)  // (-15) places the tag above the circle, adjust it according to your need
          .attr('x', x.baseVal.value)
          .attr('text-anchor', 'middle')
          .attr('class', 'c3-text c3-text-'+i)
          .text(data[i].<data point key>) // the text that needs to be added can be hard coded or fetched for the original data.
          //Since I am using a JSON to plot the data, I am referencing it and using the key of the value to be shown.
    
      }
    
    }
    
    1. 这将添加标签,但在调整大小时,将绘制多个数据标签。为了解决这个问题,在图表调整大小时,我们必须删除以前的数据标签(在图表的“onresize”属性中)。
    2. 代码段:

       onresize: function () {
                    $('.c3-shapes.c3-circles text').remove();
                 }