下面是基本上使用d3加载CSV数据并创建散点图的javascript代码。当加载html页面时,不会渲染圆,但是当我在Mac上使用firefox 65版本在调试模式下运行此圆并逐行执行代码时,圆成功渲染了圆。当我检查DOM时,没有在svg下附加圆元素,但是,在调试模式下,所有圆都附加了适当的x,y坐标。
<script type="text/javascript">
d3.csv("movies.csv").then(function(data) {
for (var i = 0; i <= data.length - 1; i++) {
winNomVsRatings.push([parseFloat(data[i]["Rating"]), parseInt([data[i]["WinsNoms"]])]);
budgetVsRatings.push([parseFloat(data[i]["Rating"]), parseInt([data[i]["Budget"]])]);
}
});
//Dynamic, random dataset
var dataset = [];
dataset = winNomVsRatings;
var w = 500;
var h = 300;
var padding = 30;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
//Create scale functions
var cScale = d3.scaleLinear()
.domain([0, 100])
.range([1,5]);
var xScale = d3.scaleLinear()
.domain([0, 10])
.range([padding , w - padding * 2]);
var yScale = d3.scaleLinear()
.domain([0, 300])
.range([h - padding , padding]);
var xAxis = d3.axisBottom(xScale);
var yAxis = d3.axisLeft(yScale);
console.log("Before Appending Circles");
console.log(dataset);
svg.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("fill", "none")
.attr("stroke", function(d){
console.log(d);
if (cScale(d[0]) > 0){
return "blue";
}else{
return "green";
}
})
.attr("cx", function(d){
return xScale(d[0]);
})
.attr("cy", function(d){
return yScale(d[1]);
})
.attr("r", function(d){
return Math.sqrt(Math.pow((cScale(d[0])), 2) + Math.pow((cScale(d[1])), 2));
});
console.log("After Appending Circles");
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")" )
.call(xAxis);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding + ",0)" )
.call(yAxis);
</script>