Reputation: 197
I'm trying to place a circle on a graph using D3.js with the below code. The axis of the graph show up fine however the circle does not. When inspecting the page in the browser I can see that the circle is added to the html but it does not show up for some reason even though I'm using fill. There is likely something simply I'm missing...
var width = 710, height = 710;
var margin = {top: -20, right: 30, bottom: 40, left: 40};
var svg = d3.select("#app")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var xAxis = d3.scaleLinear()
.domain([0, 20])
.range([ 0, width ]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xAxis));
var yAxis = d3.scaleLinear()
.domain([0, 20])
.range([ height, 0 ]);
svg.append("g")
.call(d3.axisLeft(yAxis));
svg.append('circle').selectAll("dot")
.attr('cx', 10)
.attr('cy', 10)
.attr('r', 10)
.style('fill', '#000000');
<script src="https://d3js.org/d3.v6.min.js"></script>
<canvas></canvas>
<svg id="app"></svg>
Upvotes: 1
Views: 511
Reputation: 38151
You aren't actually setting the radius or position of your circle:
svg.append('circle') // returns a selection of a newly minted circle
.selectAll("dot") // returns an empty selection (there are no dot elements in the circle to select)
.attr('cx', 10) // modify elements in the empty selection, which alters no elements, return the empty selection
.attr('cy', 10) // ditto.
.attr('r', 10) // ditto.
.style('fill', '#000000'); // ditto.
Instead, just remove the selectAll statement as you want to modify the circle, not children of it.
Also, as you are using a scale to position your data, if you want it to be positioned based on the scaled values of your x/y coordinates, you can use xAxis and yAxis to position the circle:
svg.append('circle') // returns a selection of a newly minted circle
.attr('cx', xAxis(10)) // modifies the selected elements, returns same selection.
.attr('cy', yAxis(10))
.attr('r', 10)
.style('fill', '#000000');
As seen below:
var width = 710, height = 710;
var margin = {top: -20, right: 30, bottom: 40, left: 40};
var svg = d3.select("#app")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var xAxis = d3.scaleLinear()
.domain([0, 20])
.range([ 0, width ]);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(xAxis));
var yAxis = d3.scaleLinear()
.domain([0, 20])
.range([ height, 0 ]);
svg.append("g")
.call(d3.axisLeft(yAxis));
svg.append('circle')
.attr('cx', xAxis(10))
.attr('cy', yAxis(10))
.attr('r', 10)
.style('fill', '#000000');
<script src="https://d3js.org/d3.v6.min.js"></script>
<canvas></canvas>
<svg id="app"></svg>
Upvotes: 3