在NVD3 scatterChart上绘制标签

时间:2015-03-20 02:45:40

标签: javascript d3.js nvd3.js

如果我在http://nvd3.org/examples/scatter.html的示例中有以下代码,我可以在绘制的点上添加标签吗?不是工具提示,而是将我的数据中的一个值渲染为一个始终附加到该点的标签?显然,在这个具体的例子中这样做太过拥挤,但是在人口较少的图表中,如果每个点都有一个名称,那么标记它会很棒。谢谢!

  nv.addGraph(function() {
  var chart = nv.models.scatterChart()
                .showDistX(true)    //showDist, when true, will display those little distribution lines on the axis.
                .showDistY(true)
                .transitionDuration(350)
                .color(d3.scale.category10().range());

  //Configure how the tooltip looks.
  chart.tooltipContent(function(key) {
      return '<h3>' + key + '</h3>';
  });

  //Axis settings
  chart.xAxis.tickFormat(d3.format('.02f'));
  chart.yAxis.tickFormat(d3.format('.02f'));

  //We want to show shapes other than circles.
  chart.scatter.onlyCircles(false);

  var myData = randomData(4,40);
  d3.select('#chart svg')
      .datum(myData)
      .call(chart);

  nv.utils.windowResize(chart.update);

  return chart;
});

/**************************************
 * Simple test data generator
 */
function randomData(groups, points) { //# groups,# points per group
  var data = [],
      shapes = ['circle', 'cross', 'triangle-up', 'triangle-down', 'diamond', 'square'],
      random = d3.random.normal();

  for (i = 0; i < groups; i++) {
    data.push({
      key: 'Group ' + i,
      values: []
    });

    for (j = 0; j < points; j++) {
      data[i].values.push({
        x: random()
      , y: random()
      , size: Math.random()   //Configure the size of each scatter point
      , shape: (Math.random() > 0.95) ? shapes[j % 6] : "circle"  //Configure the shape of each scatter point.
      });
    }
  }

  return data;
}

1 个答案:

答案 0 :(得分:1)

您可以添加标签。这非常俗气,但提出了一个想法:

var svg = d3.select('svg');
svg.selectAll('path')
    .each(function(scatterpoint) {
        svg.append('text')
             .x(scatterpoint.x)
             .y(scatterpoint.y)
             .text(scatterpoint.maybe_you_have_text_here);
    })