How can i made a dot chart from d3.js template 

2019-08-06 05:17发布

问题:

This question already has an answer here:

  • How to replace line in chart by serie of dot? 2 answers

I'm attempting to use the 'Reusable Charts' approach described by @mbostock, everything is fine when using a line (<path>). However, when I try to use dots (<circle>), only one element is added to the chart and it's not well formed (wrong cx and cy).

My attempted code is between lines 50-55 of the fiddle. I tried to append a circle to my svg for each data but it is not added.

回答1:

The first problem is the d3.svg.line generator takes an array as input, but a circle element only needs one value of this array. So first, you have to get the data binding right.

Next, you need to have the scales right. cx and cy can use the X and Y scale accessor functions. The radius also need a scale, because your xSpeed contains negative numbers and a radius can't be negative. So here is the fixed version: http://jsfiddle.net/christopheviau/2DDuH/6/

var speedScale = d3.scale.linear().domain(d3.extent(data.map(function(d, i){return d.xSpeed;}))).range([2, 10]);
            gEnter.selectAll('circle.dot')
                .data(function(d, i){return d})
                .enter().append("circle")
                .attr("class", "dot")
                .attr("cx", X)
                .attr("cy", Y)
                .attr("r", function(d, i){return speedScale(d.xSpeed)});


标签: charts d3.js