How to replace line in chart by serie of dot?

2019-03-01 15:50发布

问题:

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.

回答1:

great work on leveraging the reusable chart API!

In order to work with circles, the data needs to be bound to the collection of circles as well. There are a variety of ways you can take a look at selections for more information (search for array of arrays for the tricky bit that would give you some other insight on how to do it differently).

http://jsfiddle.net/7rdU7/

Above is a fix made to your example, keeping it simple and easy to understand what the differences are.

g.selectAll('.circle').data(data).enter().append("circle")
            .attr("class", "dot")
            .attr("cx", function(d) {return xScale (d.date); })
            .attr("cy", function(d) {return yScale (d.ySpeed); })
            .attr("r", function(d) {return rScale (d.xSpeed); });

If you are looking to transition between one visualization (a line) to a set of points. This is where it becomes a very tricky game of figuring out how to create a set of varying sized circles all leveraging an svg:path element. If that's the case you should look at the source of the crossfilter example to see how it is done to create several varying bar charts, though I really don't know if this is the ideal way to work with it.



回答2:

Instead of changing the path, change how the path is drawn.

Demo: http://jsfiddle.net/2DDuH/5/

 

.line {
  fill: none;
  stroke: #000;
  stroke-width: 5px;
  stroke-linecap: round;
  stroke-dasharray:0 20
}

By using a fatter stroke, a round line cap, and dashed lines that 'draw' for 0px followed by a gap, your path is stroked with a series of circles. Your stroke-width controls the diameter of your circles.

You can provide an arbitrarily complex dasharray to unevenly space them, if you want. For example, try 0 20 0 40 0 6 0 30 0 15 0 30.