ebc34
ebc34

Reputation: 21

Bubble chart without scaling

I am trying to create a bubble chart in d3.js WITHOUT scaling. i.e. need this:

What i tried is this:

var svg = d3.select('#chart'),
    width = 400,
    height = 300;

var x = d3.scaleLinear()
        .domain([0, 10])
        .range([ 0,width ]);
svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

// Add Y axis
var y = d3.scaleLinear()
        .domain([0.0, 10.0])
        .range([ height, 0]);
svg.append("g")
    .call(d3.axisLeft(y));

svg.append('g')
    .append("circle")
    .attr("cx", "5" )
    .attr("cy", "0.5" )
    .attr("r", "2")
    .style("fill", "red")
    .style("opacity", "0.7")
    .attr("stroke", "black");
#chart {
    overflow: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.2/d3.min.js"></script>

<svg id="chart" width="400" height="300"></svg>

But it is still scaling! I want the sample circle to appear at cx = 5, cy = 0.5 in the chart and have a radius of 2 but it appears somewhere random and has some random radius.

Can anyone help? as soon i understand how to do this for one point, i will be able to do this for a whole dataset easily. All tutorials i looked have scaling so im asking here

Upvotes: 1

Views: 87

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

It's not clear what you mean by "without scaling". Did you mean without scales? When you do .attr("cx", "5" ) you are simply positioning the circle at 5 pixels in the x-axis of the SVG coordinates system. Thus, if that's what you want, the chart you have is correct.

Maybe what's confusing you is that overflow: visible, it can make difficult seeing the several elements' exact positions in the SVG, so get rid of that.

On the other hand, if you set scales, use them:

.attr("cx", x(5))

Here's your code with that change:

var svg = d3.select('#chart'),
  width = 400,
  height = 300,
  marginLeft = 20;

var x = d3.scaleLinear()
  .domain([0, 10])
  .range([marginLeft, width]);
svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

// Add Y axis
var y = d3.scaleLinear()
  .domain([0.0, 10.0])
  .range([height, 0]);
svg.append("g")
  .attr("transform", "translate(" + marginLeft + ",0)")
  .call(d3.axisLeft(y));

svg.append('g')
  .append("circle")
  .attr("cx", x(5))
  .attr("cy", y(0.5))
  .attr("r", "2")
  .style("fill", "red")
  .style("opacity", "0.7")
  .attr("stroke", "black");
#chart {
  overflow: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.2/d3.min.js"></script>

<svg id="chart" width="400" height="300"></svg>

The radius is correct, there's no random radius here.

Upvotes: 1

Related Questions