Julia Park
Julia Park

Reputation: 69

very simple d3.js line graph not displaying in browser

For some reason, I cannot get a very simple line graph to display even though I'm using a code snippet from this source: https://www.dashingd3js.com/svg-paths-and-d3js

I'm fairly new to d3.

I realized the source snippet did not have an xScale or yScale variable (which some solutions on StackOverflow recommended) so I tried incorporating them into the snippet but to no avail...I'm not sure I'm even using the scale function properly. I've gotten the svg path version of this to display, but for interactivity reasons I need to convert this into d3 script.

<script src="d3.min.js"></script>

<script>

  var 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}];

  var xScale = d3.scale.linear()
    .domain([0, 300])
    .range([0, 300]);

  var yScale = d3.scale.linear()
    .domain([0, 300])
    .range([0, 300]);

  var lineFunction = d3.svg.line()
    .x(function(d) { return xScale(d.x); })
    .y(function(d) { return yScale(d.y); })
    .interpolate("linear");

  var svgContainer = d3.select("body").append("svg")
    .attr("width", 300)
    .attr("height", 300);

  var lineGraph = svgContainer.append("path")
    .attr("d", lineFunction(lineData))
    .attr("stroke", "blue")
    .attr("stroke-width", 3)
    .attr("fill", "none");

</script>

Upvotes: 2

Views: 379

Answers (1)

Halim
Halim

Reputation: 527

You are using deprecated D3 version 3 code. You can check this link to see what parts of the d3 have changed in V4 and v5.

in your code sample:

d3.scale.linear() should be d3.scaleLinear()

d3.svg.line() should be d3.line()

.interpolate("linear") should be .curve(d3.curveBasis)

Also, make sure your script is inside the <body> element, not in the <head>

Here is a corrected and tested version:

var 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}];

var xScale = d3.scaleLinear()
.domain([0, 300])
.range([0, 300]);

var yScale = d3.scaleLinear()
.domain([0, 300])
.range([0, 300]);

var lineFunction = d3.line()
.x(function(d) { return xScale(d.x); })
.y(function(d) { return yScale(d.y); })
.curve(d3.curveBasis);

var svgContainer = d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 300);

var lineGraph = svgContainer.append("path")
.attr("d", lineFunction(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 3)
.attr("fill", "none");

Upvotes: 1

Related Questions