Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

points on line in d3.js

Tags:

d3.js

I'm creating a line chart in d3.js like this:

var line = d3.svg.line()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.temperature); });

I then want to put dots on the line data points like this:

var points = svg.selectAll(".point")
        .data(cities1[0].values)
      .enter().append("svg:circle")
         .attr("stroke", "black")
         .attr("fill", function(d, i) { return "black" })
         .attr("cx", function(d, i) { return x(d.date) })
         .attr("cy", function(d, i) { return y(d.temperature) })
         .attr("r", function(d, i) { return 3 });

The result is not what I expect:

enter image description here

I then change interpolate("basis") to interpolate("cardinal") and get what I want:

enter image description here

Why did I got the wrong result with basis? How can I draw the accurate points with basis too?

EDIT: A similar (unanswered) question. Check out this jsfiddle. It will only work if changing the interpolate from basis to cardinal (or other) mode. But Cardinal has a problem that it does not respect the max height of the graph. What I'm looking for is an explanation on why some interpolation modes prevent from putting the points in the right place (and why cardinal does not respect max height).

like image 263
Yaron Naveh Avatar asked Dec 26 '12 12:12

Yaron Naveh


People also ask

What is the syntax to draw a line in D3?

To make a line, we will use the line generator of d3 by invoking d3. line() . This line generator can then be used to compute the d attribute of an SVG path element. We append path to our SVG and then specify the class as line .

How do you add a dotted line in JavaScript D3?

All we have to do is insert the following line in our JavaScript code here; svg. append("path") . attr("class", "line") .


1 Answers

This is unfortunately a property of the "basis" interpolation -- the line doesn't necessarily run through the points. There's no way of "fixing" this. Unless you absolutely need this particular interpolation, just stick with one that allows you to get the points right.

You could implement a custom interpolation that gives you access to the points the line runs through and add circles accordingly. This will require a somewhat in-depth knowledge of how d3 and line interpolators work though.

like image 126
Lars Kotthoff Avatar answered Sep 22 '22 18:09

Lars Kotthoff