1

It appears that I have loaded the data correctly from the console and converted x and y to numbers but I can't get anything to appear/append to the svg on the page. I've looked at using Rstudio's built in preview and using python to host a local server, but neither works and there aren't any error message in the console log.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3 Page Template</title>
        <script src="https://d3js.org/d3.v5.min.js"></script>
    </head>
    <body>
        <script type="text/javascript">
var w = 600;
var h = 600;
var svg = d3.select("body")
                        .append("svg")
                        //.attr("width", w)
            //.attr("height", h);
                        .attr("viewBox", [0 , 0, w, h] );
var dataset = d3.csv('data.csv',
  function(d) {
  return {
    id: d.id,
    name: d.name,
    x: +d.x,
    y: +d.y
  };
}).then(function(data) {
  console.log(data);
});
var padding = 20;
var xScale = d3.scaleLinear()
  .domain([d3.min(dataset, function(d) { return d.x; }), 
           d3.max(dataset, function(d) { return d.x; })])
  .range([padding, w - padding]);
var yScale = d3.scaleLinear()
  .domain([d3.min(dataset, function(d) { return d.y; }), 
           d3.max(dataset, function(d) { return d.y; })])
  .range([h - padding, padding]);
var lights = svg.selectAll('circle')
   .data(dataset)
   .enter()
   .append('circle')
    .attr("cx", function (d) {
      return xScale(d.x); 
    } )
    .attr("cy", function (d) { return yScale(d.y); } )
    .attr("r", 15)
    .style("fill", "yellow")
    .style("stroke", "grey")    
    });
var text = svg.selectAll("text")
    .data(dataset)
    .enter()
    .append("text")
    .attr("x", function (d) {
      console.log(d.x);
      return xScale(d.x);})
    .attr("y", function (d) {return yScale(d.y) + 30;})
    .text(function (d) {return d.name;})
    .attr("font-size", "10px")
    .attr('text-anchor', 'middle');
        </script>
    </body>
</html>
troh
  • 1,354
  • 10
  • 19
  • 1
    In short: `var dataset = d3.csv('data.csv' etc...` will not do what you think it will. Your `dataset` will be just a promise, not the fetched CSV. The solution is just putting all your code inside the `then()` and using `data` as the data array. – Gerardo Furtado Jul 28 '20 at 03:09
  • By all my code, do you mean everything that is in there? I read the other associated post but it is still unclear to me how to actually use a "promise". – troh Jul 28 '20 at 05:29
  • 1
    No! Everything from `var padding = 20;` to the last `attr()`. In other words: everything that depends on `data`. And don't forget to change `dataset` to `data` (alternatively, just change the parameter name from `data` to `dataset`). – Gerardo Furtado Jul 28 '20 at 05:31

0 Answers0