Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using nvd3 to plot some series and want to add some arbitrary rectangles to the plot. How can I access the underlying x- and y-scale for the d3 plot so I can transform my rectangles' coordinates into the svg pixel coordinates so that are on the same scale as the existing data:

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;
});
like image 886
nickponline Avatar asked Jan 31 '26 17:01

nickponline


1 Answers

You can access the scales through the axes, i.e. chart.xAxis.scale() and so on. To apply those to your coordinates, you would do something like

.attr("x", chart.xAxis.scale()(50));
like image 151
Lars Kotthoff Avatar answered Feb 02 '26 22:02

Lars Kotthoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!