回调函数draw
似乎无法访问提供给d3.csv()
的回调内的数据。在回调console.log
中打印:
data:null
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Correlation XX</title>
<script src="d3v4.js"></script>
<script type="text/javascript">
function draw(data) {
console.log("data: " + data); // <-- talking about this line
var width = 860,
height = 500;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(50, 50)");
}
</script>
</head>
<body>
<script type="text/javascript">
d3.csv("modified_data_titanic.csv", function(data) {
data.forEach(function(d) {
d.Age = +d.Age;
d.Survived = +d.Survived;
});
}, draw);
</script>
</body>
</html>
csv-data:
"","PassengerId","Survived","Pclass","Name","Sex","Age","SibSp","Parch","Ticket","Fare","Cabin","Embarked","Child","Survived_new","Category"
"1",1,0,3,"Braund, Mr. Owen Harris","male",22,1,0,"A/5 21171",7.25,"","S","FALSE",0,"20-29 m"
"2",2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs Thayer)","female",38,1,0,"PC 17599",71.2833,"C85","C","FALSE",0,"30-39 f"
"3",3,1,3,"Heikkinen, Miss. Laina","female",26,0,0,"STON/O2. 3101282",7.925,"","S","FALSE",0,"20-29 f"
"4",4,1,1,"Futrelle, Mrs. Jacques Heath (Lily May Peel)","female",35,1,0,"113803",53.1,"C123","S","FALSE",0,"30-39 f"
"5",5,0,3,"Allen, Mr. William Henry","male",35,0,0,"373450",8.05,"","S","FALSE",0,"30-39 m"
"6",6,0,3,"Moran, Mr. James","male",NA,0,0,"330877",8.4583,"","Q",NA,0,NA
"7",7,0,1,"McCarthy, Mr. Timothy J","male",54,0,0,"17463",51.8625,"E46","S","FALSE",0,"50-59 m"
"8",8,0,3,"Palsson, Master. Gosta Leonard","male",2,3,1,"349909",21.075,"","S","TRUE",0,"0-9 m"
"9",9,1,3,"Johnson, Mrs. Oscar W (Elisabeth Vilhelmina Berg)","female",27,0,2,"347742",11.1333,"","S","FALSE",0,"20-29 f"
"10",10,1,2,"Nasser, Mrs. Nicholas (Adele Achem)","female",14,1,0,"237736",30.0708,"","C","TRUE",0,"10-19 f"
"11",11,1,3,"Sandstrom, Miss. Marguerite Rut","female",4,1,1,"PP 9549",16.7,"G6","S","TRUE",0,"0-9 f"
"12",12,1,1,"Bonnell, Miss. Elizabeth","female",58,0,0,"113783",26.55,"C103","S","FALSE",0,"50-59 f"
"13",13,0,3,"Saundercock, Mr. William Henry","male",20,0,0,"A/5. 2151",8.05,"","S","FALSE",0,"20-29 m"
背景信息:我的实际目标是使用 Age 或 Survived 等列作为x轴的范围。
答案 0 :(得分:1)
您的行转换功能,即d3.csv()
的第二个参数,不正确。有关详细信息,请查看documentation:
如果指定了行转换函数,则为每一行调用指定的函数,传递一个表示当前行(
d
)的对象,即索引({{1} })从第一个非标题行开始为零,以及列名称数组。如果返回的值为null或未定义,则跳过该行,并且将从 dsv .parse;返回的数组中省略该行。否则,返回的值定义相应的行对象。
有两个问题:
为每一行调用该函数,而不是像调用函数那样调用整个数据。
Adrian在他的comment中指出,你需要返回行的值;否则,将跳过该行。
以下功能应该可以解决问题:
i
答案 1 :(得分:1)
您的访问者(或行)功能不正确。
首先,访问者功能不需要forEach
。除此之外,你必须返回每一行。总之,这些是变化:
d3.csv("modified_data_titanic.csv", function(d) {
d.Age = +d.Age;
d.Survived = +d.Survived;
return d;
}, draw);