Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.svg.line() error: Uncaught TypeError: Cannot read property 'line' of undefined

I am using the following code to try to draw a path using d3.js I have tried various code examples on the web about the same and have been getting the same error everywhere.

Following is the JS:

<script type="text/javascript">     var svg;     //The data for our line  lineData = [ { "x": 1,   "y": 5},  { "x": 20,  "y": 20},                  { "x": 40,  "y": 10}, { "x": 60,  "y": 40},                  { "x": 80,  "y": 5},  { "x": 100, "y": 60}];  //This is the accessor function we talked about above var lineFunction = d3.svg.line()                          .x(function(d) { return d.x; })                          .y(function(d) { return d.y; })                          .interpolate("linear");  //The SVG Container var svgContainer = d3.select("body").append("svg:svg")                                     .attr("width", 200)                                     .attr("height", 200);  //The line SVG Path we draw var lineGraph = svgContainer.append("path")                             .attr("d", lineFunction(lineData))                             .attr("stroke", "blue")                             .attr("stroke-width", 2)                             .attr("fill", "none");     </script> 

The error is: Uncaught TypeError: Cannot read property 'line' of undefined

This comes at the following line: var lineFunction = d3.svg.line()

I am not sure what 'undefined' means here. Any leads?

like image 656
Arihant Avatar asked Jun 03 '16 16:06

Arihant


1 Answers

Reading your comment I suppose you are using D3 v4. As of version 4 there is no d3.svg, hence the error message. The line generator you are looking for is now defined as d3.line().

If you were still using version 3, it would be d3.svg.line() instead.


Also, as other answerers have noted, this will lead to a follow-up error when leaving the rest of the statement untouched as d3.line does not feature a method .interpolate(). D3 v4 has curve factories for this purpose, which are used for interpolation. These factories are supplied to the line generator using line.curve(). D3 v3's .interpolate("linear") now becomes .curve(d3.curveLinear). However, since line.curve() defaults to d3.curveLinear this can safely be omitted in your case.

The statement thus becomes:

var lineFunction = d3.line()   .x(function(d) { return d.x; })   .y(function(d) { return d.y; })   .curve(d3.curveLinear);          // Use for clarity, omit for brevity. 
like image 63
altocumulus Avatar answered Oct 01 '22 02:10

altocumulus