moman822
moman822

Reputation: 1954

D3 - set axes with percent scale

I am attempting to create a scatterplot whereby the dimensions of the appended svg element are set by percent (so it takes up say 50 or 100% of the screen rather than X number of pixels).

Then I want to populate the svg element with circles whose positions are scaled to be in between 0 and 100 and set as a percent as well, like so: .attr('cx', function(d){return xScale(d[0]) + '%'})

This approach works for setting the circle positions, but I cannot get the correct scaling on the axes. I think they are set via the transform element, and this does not want to take % as part of an argument.

See the js fiddle here with a full example: https://jsfiddle.net/s01pg3fa/5/

The axes are not scaled correctly to fill out the entire svg element. Thanks for any input.

Upvotes: 1

Views: 966

Answers (1)

Marcelo
Marcelo

Reputation: 4282

You can get the client size of the svg and use it in the axis scales:

var svgClientSize = svg.node().getBoundingClientRect();

Using it on the axis scales:

var xScale = d3.scaleLinear()
            .domain([0, d3.max(data, function(d){return d[0]})])
            .range([padding,svgClientSize.width-padding])
var yScale = d3.scaleLinear()
            .domain([0, d3.max(data, function(d){return d[1]})])
            .range([svgClientSize.height-padding,padding])

In this case, you do not need the '%' for the circles

Here is the updated js fiddle:https://jsfiddle.net/q7xm8n73/1/

Upvotes: 2

Related Questions