Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript D3js如何格式化表中某些列的内容_Javascript_D3.js - Fatal编程技术网

Javascript D3js如何格式化表中某些列的内容

Javascript D3js如何格式化表中某些列的内容,javascript,d3.js,Javascript,D3.js,我有一个用d3制作的交互式表格的代码,它运行得很好。唯一的问题是,我希望第二列和第三列的内容显示为百分比。 我正在使用的csv文件如下所示: CSV date,kind1,kind2,place 17/03/2014,0.28,0.46,NY .... 我想我需要再次使用map函数,但我感到困惑,有什么帮助吗 var table = d3.select("body") .append("table") .attr("class", "table"), thead

我有一个用d3制作的交互式表格的代码,它运行得很好。唯一的问题是,我希望第二列和第三列的内容显示为百分比。 我正在使用的csv文件如下所示:

CSV
date,kind1,kind2,place
17/03/2014,0.28,0.46,NY
....  
我想我需要再次使用map函数,但我感到困惑,有什么帮助吗

 var table = d3.select("body")
    .append("table")
    .attr("class", "table"),
    thead = table.append("thead"),
    tbody = table.append("tbody");

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

var columns = Object.keys(data[0])

var header = thead.append("tr")
    .selectAll("th")
    .data(columns)
    .enter()
    .append("th")
        .text(function(d){ return d;});

var rows = tbody.selectAll("tr")
    .data(data)
    .enter()
    .append("tr")
    .on("mouseover", function(d){
        d3.select(this)
            .style("background-color", "orange");
    })
    .on("mouseout", function(d){
        d3.select(this)
            .style("background-color","transparent");
    });

var cells = rows.selectAll("td ")
    .data(function(row){
        return columns.map(function(d, i){
            return {i: d, value: row[d]};
        });
    })
    .enter()
    .append("td")
    .html(function(d){ return d.value;});`

`

实现目标的一种方法是更改最后一行的回调:

.html(function(d){ return d.value;})
为此:

.html(function(d,i){ if(i == 1 || i == 2) return (d.value*100) + '%'; return d.value; })
这利用了d3调用所有具有数据和索引的函子的方式。根据您的数据,可能有比查看索引更好的方法


或者,您可以在读取数据后提前添加百分比符号:

data.forEach(function(d) { d[1] = (d[1]*100)+'%'; d[2] = (d[2]*100)+'%'; })

这种方法限制了您以后使用数据进行其他计算的能力。

我建议将最后一行更改为:

.html(function(d){ return typeof(d.value)==="number"?(100*d.value).toFixed(1)+"%":d.value;});

这会将所有数字类型的属性(在您的案例中为kind1和kind2)更改为百分比,小数精度在
.toFixed()
调用的参数中给出。

OP的数据集中不太可能有NaN,但是请记住,
typeof NaN===“number”
返回true。您是知道数据的人。如果这可能是一个问题,那么
typeof(d.value)==“string”
和交换三元运算符中的命令如何?我不知道任何数据,我不是OP。我只是告诉你
typeof
将为NaN返回“number”。对不起,@GerardoFurtado,我向OP发送了这个消息,尽管我在回复你的评论。您的观点完全正确,但即使数据集包含一些NaN元素,我认为我的建议也可以纠正,然后它提供了一个解决方案,它不是基于列索引的,而是依赖于数据集的内容。您可以使用:
d3.format('.1%')(d.value)