如何访问 nvd3 中 d3 图的 x 和 y 尺度

How do I access the x- and y-scale of the d3 plot in nvd3?

本文关键字:图的 d3 尺度 nvd3 何访问 访问      更新时间:2023-09-26

我正在使用 nvd3 绘制一些系列,并希望在绘图中添加一些任意矩形。如何访问 d3 图的基础 x 和 y 刻度,以便将矩形的坐标转换为 svg 像素坐标,以便与现有数据处于同一比例:

function d3_render(response) {
nv.addGraph(function() {
  var data  = response;

  chart.xAxis
      .axisLabel('Time (s)')
      .tickFormat(d3.format(',f'));
  chart.x2Axis
      .tickFormat(d3.format(',f'));

  chart.yAxis
      .axisLabel('Units normalized')
      .tickFormat(d3.format(',.2f'));
  chart.y2Axis
      .tickFormat(d3.format(',.2f'));
  d3.select('#chart svg')
      .datum(data)
    .transition().duration(1000)
      .call(chart);
  // Adding my rectangle here ...
  d3.select('#chart svg')
      .append('g')
      .append('rect')
      .attr('x', 50) // need to transform to same scale.
      .attr('y', 50) // need to transform to same scale.
      .attr('width', 100) // need to transform to same scale.
      .attr('height', 100) // need to transform to same scale.
      .attr('fill', 'red')

  nv.utils.windowResize(chart.update);
  return chart;
});

您可以通过轴访问刻度,即 chart.xAxis.scale()等等。要将它们应用于您的坐标,您可以执行以下操作:

.attr("x", chart.xAxis.scale()(50));