在NVD3散点图上绘制标签

Plotting Labels on NVD3 scatterChart

本文关键字:绘制 标签 散点图 NVD3      更新时间:2023-09-26

如果我在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;
}

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

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