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

前提是你 提交于 2019-12-06 07:31:34

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/19392688/how-do-i-access-the-x-and-y-scale-of-the-d3-plot-in-nvd3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!