Reputation: 28800
I have drawn x axis an y axis in d3.
var margin = {top: 20, right: 100, bottom: 30, left: 100},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var xScale = d3.scale.linear()
.domain([0, 15])
.range([0, width]);
var yScale = d3.scale.linear()
.domain([0, 38])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.innerTickSize(-height)
.outerTickSize(0)
.tickPadding(10);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.innerTickSize(-width)
.outerTickSize(0)
.tickPadding(10);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
I then want to draw a line between 2 points in this grid.
svg.append('line')
.style('stroke', 'black')
.attr('x1', 5)
.attr('y1', 5)
.attr('x2', 20)
.attr('y2', 20);
Here is a jsbin of the results.
So the line is not drawn between the grid coordinates (5, 5) and (20, 20).
How can I place the line on the coordinates of the grid that I have created?
Upvotes: 2
Views: 4107
Reputation: 2698
I solved it this way:
svg.append('line')
.style('stroke', 'black')
.attr('x1', function (d) { return x(5))
.attr('y1', function (d) { return y(5))
.attr('x2', function (d) { return x(20))
.attr('y2', function (d) { return y(20));
Upvotes: -1
Reputation: 21578
You are using xScale
and yScale
when setting up your axes. Apart from being used internally for generating ticks and tick labels these scales will provide easy means of conversion between your SVG's coordinates (the scale's range) and the coordinates used by your grid (the scale's domain), i.e. the values of your data.
To draw the line, you need to apply the scales to the data values as well:
svg.append('line')
.style('stroke', 'black')
.attr('x1', xScale(5))
.attr('y1', yScale(5))
.attr('x2', xScale(20))
.attr('y2', yScale(20));
Upvotes: 5
Reputation: 18744
Something's wrong in the way you're calculating vertical axis coordinates,
check this :
svg.append('line')
.style('stroke', 'black')
.attr('x1', 5)
.attr('y1', height -5 )
.attr('x2', 20)
.attr('y2', height - 20);
Upvotes: 0