【问题标题】:How to make a scatter plot from a CSV file using d3.js?如何使用 d3.js 从 CSV 文件制作散点图?
【发布时间】:2013-03-27 19:01:21
【问题描述】:

我对 d3.js 很陌生。我正在尝试使用 csv 文件中存在的数据制作散点图。在 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

请帮帮我。

【问题讨论】:

    标签: csv d3.js visualization scatter-plot


    【解决方案1】:

    大部分看起来都不错。我能看到的唯一问题(尽管我可能还缺少其他问题)接近尾声:

    // 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")

    【讨论】:

    • 感谢您的回答。我纠正了所有这些,但它仍然显示一个空白页。
    • @user2019940 嗯......超出这一点,如果没有工作的 jsFiddle,真的不可能调试它。那里的代码太多了。
    猜你喜欢
    • 1970-01-01
    • 2017-03-28
    • 2021-07-02
    • 2019-06-26
    • 1970-01-01
    • 2022-11-24
    • 2023-03-10
    • 1970-01-01
    • 2013-05-18
    相关资源
    最近更新 更多