2013-03-27 256 views
0

我對d3.js很新穎。我正在嘗試使用csv文件中存在的數據製作散點圖。從csv文件中,我使用了來自兩列的數據。如何使用d3.js從CSV文件製作散點圖?

d3.csv("test.csv",function (data) { 

    var margin = {top: 30, right: 10, bottom: 50, left: 60}, 
     width = 960 - margin.left - margin.right, 
     height = 500 - margin.top - margin.bottom; 

     var xMax = d3.max(data, function(d) { return +d.Survivaltime; }), 
     xMin = 0, 
     yMax = d3.max(data, function(d) { return +d.Year; }), 
     yMin = 1950; 

     //Define scales 
    var x = d3.scale.linear() 
     .domain([xMin, xMax]) 
     .range([0, width]); 

    var y = d3.scale.linear() 
     .domain([yMin, yMax]) 
     .range([height, 0]); 
}); 


// the chart object, includes all margins 
var chart = d3.select('body') 
.append('svg:svg') 
.attr('width', width + margin.right + margin.left) 
.attr('height', height + margin.top + margin.bottom) 
.attr('class', 'chart') 

// the main object where the chart and axis will be drawn 
var main = chart.append('g') 
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')') 
.attr('width', width) 
.attr('height', height) 
.attr('class', 'main') 

// draw the x axis 
var xAxis = d3.svg.axis() 
.scale(x) 
.orient('bottom'); 
.tickSize(-height) 
.tickFormat(d3.format("s")); 

main.append('g') 
.attr('transform', 'translate(0,' + height + ')') 
.attr('class', 'main axis date') 
.call(xAxis); 

// draw the y axis 
var yAxis = d3.svg.axis() 
.scale(y) 
.orient('left'); 
.ticks(5) 
.tickSize(-width) 
.tickFormat(d3.format("s")); 


main.append('g') 
.attr('transform', 'translate(0,0)') 
.attr('class', 'main axis date') 
.call(yAxis); 


// draw the graph object 
var svg = main.append("svg:g"); 

g.selectAll("scatter-dots") 
    .data(d.Year) // using the values in the ydata array 
    .enter().append("svg:circle") // create a new circle for each value 
     .attr("cy", function (d) { return y(d.Year); }) // translate y value to a pixel 
     .attr("cx", function (d) { return x(d.Survivaltime); }) // translate x value 
     .attr("r", 10) // radius of circle 
     .style("opacity", 0.6); // opacity of circle 

這裏'山鏈接到CSV文件:

http://bit.ly/14oLdml

請幫助我。

回答

0

大部分看起來不錯。我可以看到(雖然有可能被別人認爲我失蹤)唯一的問題是接近尾聲:

// draw the graph object 
//var svg = main.append("svg:g");// <---- this is causing a bug. Should be: 
var g = main.append("svg:g"); 

然後修復:

g.selectAll(".scatter-dots"); // <---- added a period before scatter-dots 

的另一件事,這是不破壞你的代碼,但應該修正:

之後你.append("svg:circle"),你應該打電話給.attr("class", "scatter-dots")就可以了。

+0

感謝您的回答。我糾正了所有這些,但仍然顯示空白頁。 – user2019940 2013-03-27 19:59:53

+0

@ user2019940呃......超越這一點,如果沒有工作的jsFiddle,真的不可能進行調試。那裏的代碼太多了。 – meetamit 2013-03-27 20:26:04