来自csv的D3填充数据集失败

时间:2016-10-05 13:22:40

标签: javascript d3.js

我是D3的新手,但我正在尝试将一些bl.ock代码转换为我的要求。

我使用的示例在html文件中有一个静态数据字典 - 我试图将其切换为使用来自csv的数据。

我的csv如下:

类,测量
山姆,0.3
彼得,0.25
约翰,0.15
里克,0.05
莱尼,0.18
保罗,0.04
史蒂夫,0.03

我尝试过的代码如下:

var dataset = d3.map();
dataset = d3.csv("http://blahblah/testingtesting/DThree/PieChart.csv"
                , function(d) { dataset.set(d.category, +d.measure); }) 

function dsPieChart() {

    var width = 400,
        height = 400,
        outerRadius = Math.min(width, height) / 2,
        innerRadius = outerRadius * .999,
        // for animation
        innerRadiusFinal = outerRadius * .5,
        innerRadiusFinal3 = outerRadius * .45,
        color = d3.scale.category20() 
    ;

    var vis = d3.select("#pieChart")
        .append("svg:svg")
        .data([dataset])
        .attr("width", width)
        .attr("height", height)
        .append("svg:g") 
        .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")")
    ;
    ..
    ...
    ....

使用上述内容时不会出现饼 - 是否存在范围问题,因为dsPieChart()之外的填充数据集意味着它无法访问,或者我只是没有正确使用d3.csv?

请注意

原始代码如下所示:

function dsPieChart() {

    var dataset = [{
        category: "Sam",
        measure: 0.30
    }, {
        category: "Peter",
        measure: 0.25
    }, {
        category: "John",
        measure: 0.15
    }, {
        category: "Rick",
        measure: 0.05
    }, {
        category: "Lenny",
        measure: 0.18
    }, {
        category: "Paul",
        measure: 0.04
    }, {
        category: "Steve",
        measure: 0.03
    }];



    var width = 400,
        height = 400,
        outerRadius = Math.min(width, height) / 2,
        innerRadius = outerRadius * .999,
        // for animation
        innerRadiusFinal = outerRadius * .5,
        innerRadiusFinal3 = outerRadius * .45,
        color = d3.scale.category20() //builtin range of colors
    ;


    var vis = d3.select("#pieChart")
        .append("svg:svg") //create the SVG element inside the <body>
        .data([dataset]) //associate our data with the document
        .attr("width", width) //set the width and height of our visualization (these will be attributes of the <svg> tag
        .attr("height", height)
        .append("svg:g") //make a group to hold our pie chart
        .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")") //move the center of the pie chart from 0, 0 to radius, radius
    ;

1 个答案:

答案 0 :(得分:1)

尝试这种方式:

d3.csv("file.csv", function(rows)
    {
        //rows is an array of json objects containing the data in from the csv
        dataset = rows.map(function(d)
        {
            //each d is one line of the csv file represented as a json object                
            return {"category": d.category, "measure": +d.measure} ;
        })
       dsPieChart();
    })

here

中获取提示