繁体   English   中英

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

[英]D3js How to format the content of some columns in a table

我有一个用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()调用的参数中给出十进制精度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM