简体   繁体   English

为 Titanic 可视化加载数据时遇到问题

[英]Trouble Loading Data for Titanic Visualization

Having some massive trouble getting my D3 scatter plot visualization running.在运行我的 D3 散点图可视化时遇到了一些巨大的麻烦。 Didnt know how to reference the data, so its available from adropbox link here .不知道如何引用数据,因此可以从此处保管箱链接获得

There are a few problems.有几个问题。

  1. I am a bit confused about loading my data.我对加载我的数据有点困惑。

    • I cannot seem to get the data loaded.我似乎无法加载数据。 I have been successful before, but I am trying to load the data without having to reference a function (ie, global).我以前成功过,但我试图在不必引用函数(即全局)的情况下加载数据。 However, as you will see - I am getting nothing - [].但是,正如您将看到的 - 我什么也没得到 - []。
    • Do I need to load it at the bottom of my script and then reference the function within the d3.csv(function(d) {...}, FUNCTION);?我是否需要在脚本底部加载它,然后在 d3.csv(function(d) {...}, FUNCTION); 中引用该函数? Why cant I simple load it to a variable (as I am trying to) at the top of my script.为什么我不能简单地将它加载到脚本顶部的变量(正如我所尝试的那样)。 Such that its the first object available?这样它的第一个可用对象?
  2. I also felt like I had a good handle on the Mike Bostock tutorial about .enter(), update(), .exit().我也觉得我对 Mike Bostock 教程中关于 .enter()、update()、.exit() 的教程有很好的把握。 But I know that I have an issue in the comment section of "//ENTER + UPDATE" where I have circle.circle(function(d) {return d;});.但我知道我在“//ENTER + UPDATE”的评论部分有一个问题,我有 circle.circle(function(d) {return d;});。 I dont understand this.我不明白这一点。

Overall, I am looking to create a scatter plot with fare as my x-axis, age as my y-axis, then loop through the options of "Female Only", "Male Only", "Children Only" and "All" (starting and ending with All).总的来说,我希望创建一个散点图,以票价为 x 轴,以年龄为 y 轴,然后循环选择“仅限女性”、“仅限男性”、“仅限儿童”和“所有”(以 All 开头和结尾)。

I plan to add more to this as I get a better understanding of where I am currently stumbling.我计划添加更多内容,因为我可以更好地了解我目前遇到的困难。

 d3.csv("titanic_full.csv", function(d) { return { fare: +d.fare, age: d.age == '' ? NaN : +d.age, sibsp: +d.sibsp, pclass: +d.pclass, sex: d.sex, name: d.name, survived: d.survived }; }, function(error, d) { //Filter out erroneous age values (263 rows are removed) var dataset = d.filter(function(d) { if (d['age'] >= 0) { return d; } }); //*Main Elements Setup* //Width and height var w = 650; var h = 650; var padding = 20; //Create scale functions var xScale = d3.scale.linear() .domain([0, d3.max(dataset, function(d) { return d.fare; })]) .range([padding, w - padding * 2]); // introduced this to make sure values are not cut off var yScale = d3.scale.linear() .domain([0, d3.max(dataset, function(d) { return d.age; })]) .range([h - padding, padding]); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); var yAxis = d3.svg.axis() .scale(yScale) .orient("left"); //Create SVG element var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); //Show Axes svg.append('g') .attr('class', 'x axis') .attr('transform', 'translate(0,' + (h - padding) + ')') .call(xAxis); svg.append('g') .attr('class', 'y axis') .attr('transform', 'translate(' + padding + ',0)') .call(yAxis); function update(dataset) { //DATA JOIN //Join new data with old elements, if any. var circle = svg.selectAll('circle') .data(dataset); //UPDATE //Update old elements as needed. circle.attr('class', 'update'); //ENTER //Create new elements as needed. circle.enter().append('circle') .attr('class', 'enter') .transition() .duration(1000) .attr("cx", function(d) { return xScale(d.fare); }) .attr("cy", function(d) { return yScale(d.age); }) .attr("r", 6) .attr('fill', function(d) { if (d.survived === '0') { return 'green'; } else { return 'red'; } }) //ENTER + UPDATE //Appending to the enter selection expands the update selection to include //entering elements; so, operations on the update selection after appending to //the enter selection will apply to both entering and updating nodes. circle.circle(function(d) { return d; }); //EXIT //Remove old elements as needed. circle.exit().remove(); }; //The initial display. update(dataset); //Work through each selection var options = ['Female Only', 'Male Only', 'Children Only', 'All'] var option_idx = 0; console.log('next') var option_interval = setInterval(function(options) { if (options == 'Female Only') { var filteredData = dataset.filter(function(d) { if (d['sex'] == 'female') { return d; } }) } else if (options == 'Male Only') { var filteredData = dataset.filter(function(d) { if (d['sex'] == 'male') { return d; } }) } else if (options == 'Children Only') { var filteredData = dataset.filter(function(d) { if (d['age'] <= 13) { return d; } }) } else if (options == 'All') { var filteredData = dataset.filter(function(d) { return d; }) }; console.log('interval') option_idx++; // increment by one update(filteredData); if (option_idx >= options.length) { clearInterval(option_interval); }; }, 1500); });
 .axis path, .axis line { fill: none; stroke: black; shape-rendering: crispEdges; } .axis text { font-family: sans-serif; font-size: 8px; }
 <title>Titanic Visualization - Fare and Age Survival</title>

You should write the whole code inside the d3.csv callback function.您应该在d3.csv回调函数中编写整个代码。 Try this way.试试这个方法。

d3.csv("titanic_full.csv", function(d) {
  return {
    fare: +d[fare],
    age: d.age == '' ? NaN : +d.age,
    sibsp: +d.sibsp,
    pclass: +d.pclass
  };
}, function(error, dataset) {
  //Filter out erroneous age values (263 rows are removed)
  var dataset = dataset.filter(function(d) {
    if (d['age'] >= 0) {
      return d;
    }
  });
  //Remaining code
});

Refer here for more details.有关更多详细信息,请参阅此处

Okay, so I have an answer, but I probably will not explain this as well.好的,所以我有了答案,但我可能也不会对此进行解释。

1. I am a bit confused about loading my data. 1. 我对加载我的数据有点困惑。

With the help of @Gilsha, I was able to reconfigure my script to load the data first, with the rest of my script being the 'callback' portion of the d3.csv function.在@Gilsha 的帮助下,我能够重新配置脚本以首先加载数据,脚本的其余部分是 d3.csv 函数的“回调”部分。 That worked smoothly.那工作顺利。 I also was able to filter my data to remove the blanks right away.我还能够过滤我的数据以立即删除空白。 Here is that first part:这是第一部分:

d3.csv("titanic_full.csv", function(d) {
          return {
            fare: +d.fare,
            age: d.age == '' ? NaN : +d.age,
            sibsp: +d.sibsp,
            pclass: +d.pclass,
            sex: d.sex,
            name: d.name,
            survived: d.survived

          };
        }, function(error, d) {
          //Filter out erroneous age values (263 rows are removed)
          var dataset = d.filter(function(d) {
            if (d['age'] >= 0) {
              return d;
            }
          });

            //Rest of script here.

**2. **2. I also felt like I had a good handle on the Mike Bostock tutorial about .enter(), update(), .exit().我也觉得我对 Mike Bostock 教程中关于 .enter()、update()、.exit() 的教程有很好的把握。 Link to Bostock Tutorial I was following **链接到我正在关注的 Bostock 教程**

Couple things that I did wrong here that was holding me up.我在这里做错的几件事阻碍了我。 The main item that I was stuck on was this portion:我被卡住的主要项目是这部分:

//ENTER + UPDATE
                //Appending to the enter selection expands the update selection to include
                //entering elements; so, operations on the update selection after appending to
                //the enter selection will apply to both entering and updating nodes.
                circle.circle(function(d) {return d;});

Basically, I was following the tutorial too closely and didnt realize that when he was using "text.text(function(d) {return d;});", he was setting the text attribute (?) to something.基本上,我太密切地关注教程,并没有意识到当他使用“text.text(function(d) {return d;});”时,他将文本属性(?)设置为某些东西。 This is where I believe I should be setting any changes to my ENTER and UPDATE selections (all the items that I expect to be in the DOM).这是我认为我应该对我的 ENTER 和 UPDATE 选择(我希望在 DOM 中的所有项目)进行任何更改的地方。 So, when Mike was doing text.text and I replicated with circle.circle, I should have had circle.text(.....).所以,当 Mike 在做 text.text 并且我用 circle.circle 复制时,我应该有 circle.text(.....)。 Or whatever I want there.或者我想要的任何东西。 Anyone care to comment or explain that better??有人愿意评论或更好地解释吗?

PS - I had many other errors... throughout, especially in the section of establishing my interval! PS - 我还有很多其他的错误......在整个过程中,尤其是在建立我的间隔的部分!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM