从csv读取的Javascript d3 [英] Javascript d3 reading from csv

查看:91
本文介绍了从csv读取的Javascript d3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我是一个javascript的菜鸟,我需要从csv读取数据,用d3制作条形图。条形图对我来说没问题,从csv文件读取是。这是我的代码:

Ok, so I am a bit of a noob with javascript and I need to read data from a csv to make a barchart with d3. The barchart is no problem for me, the reading from the csv file is. This is my code:

var dataset;
    d3.csv("gender_ratio.csv", function(data) {
    dataset = data;
    return dataset;
});

var add = function(year, total, males, females){
    var year = {
        year: year,
        total: total,
        males: males,
        females: females
    };
    newdata.push(year);
    return newdata;
};

for (var i = 0; i < dataset.length; i += 4){
    add(dataset[i], dataset[i+1], dataset[i+2], dataset[i+3]);
    return newdata;
};

有人可以告诉我这里出了什么问题吗?我用modzilla firefox运行它,所以浏览器安全性不是问题。

Can someone tell me what I is going wrong here? I am running this with modzilla firefox, so the browser security isn't the problem here.

推荐答案

首先,d3的 .csv 函数异步,因此您需要在 .csv 函数中调用te实际条形图绘制函数。如果csv文件的第一行包含列名,则可以使用回调函数:

First, d3's .csv function works asynchronous, thus you need to call te actual bar chart drawing function within the .csv function. If the csv file has a first row featuring column names, you can use a callback function:

var dataset = [];
d3.csv("gender_ratio.csv", function(d) {
  return {
    year: d.year,
    total: d.total,
    males: d.males,
    females: d.females,
  };
}, function(error, rows) {
  dataset = rows;
  drawBarChart();  /* <<-- This would be the call to the drawing function. */
});

这篇关于从csv读取的Javascript d3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆