简体   繁体   中英

Can't see circles in d3.js

I'm trying to create a scatter plot and while my axes are rendered, I can't see any circles. I can't figure out what's wrong.

I realized that my data values are in string so I used '+' operator. Still doesn't work. There is no error message. I can see the elements in debug window being created but they are not displayed.

Here is my code:

function visualize(data) {

var margin = { top: 20, bottom: 80, right:50, left: 70 };
var width = 720 - margin.left + margin.right, height = 500 - margin.top - margin.bottom;

var svg = d3.select("body")
    .append("svg")
    .attr("height", height + margin.top + margin.bottom)
    .attr("width", width + margin.right + margin.left);

g=svg.append("g")
    .attr("transform","translate("+margin.left+","+margin.top+")");

var xScale = d3.scaleLinear().domain(d3.extent(data,function(d) {
    return +d.FTAG;
})).range([0, width]);

var yScale = d3.scaleLinear().domain([0,d3.max(data,function(d) { return +d["AF"]; })]).range([height, 0]);

var xAxis = d3.axisBottom(xScale);
var yAxis = d3.axisLeft(yScale);

g.append("g").attr("class", "x-axis").attr("transform", "translate(0," + height + ")").call(xAxis);
g.append("g").attr("class", "y-axis").attr("transform", "translate(0,0)").call(yAxis);

d3.selectAll("dot").data(data)
    .enter()
    .append("g")
    .append("circle")
    .attr("r", 20)
    .attr("cx",
        function(d) {
            return xScale(+d.FTAG);
        })
    .attr("cy",
        function(d) {

         return yScale(+d.AF);
    })
    .style("fill",
        function(d) {
            if (+d.AF >= 20) {
                return "red";
            } else
                return "steelblue";
        })
    .style("stroke","black")
    .style("stroke-width",1.5);
}

In your code...

d3.selectAll("dot")
    .data(data)
    .enter()
    .append("g")

... doesn't append groups anywhere.

It has to be:

svg.selectAll("dot")
    .data(data)
    .enter()
    .append("g")

Since svg is the selection that appends an SVG to the <body> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM