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