Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

sorting - D3 sort() with CSV data

I am trying all kinds of ways to make .sort() work on my csv dataset. No luck.

I'd just like to sort my data by a "value" column.

This is the function I'm running inside my d3.csv api call and before I select the dom and append my divs:

dataset = dataset.sort(function (a,b) {return d3.ascending(a.value, b.value); });

Before I get to the .sort, I clean the data:

dataset.forEach(function(d) {
            d.funded_month = parseDate(d.funded_month);
            d.value = +d.value;
        });
    };

Everything seems in order. When I console.log(d3.ascending(a.value, b.value)), I get the right outputs:

-1 d32.html:138
1 d32.html:138
-1 d32.html:138
1 d32.html:138
etc..

Yet the bars data doesn't sort.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is not clear from the provided code but I will hazard a guess you are not handling async nature of d3.csv.

This plunkr shows your sort code working fine. Note where the data object is declared, populated, and used.

here is a partial listing. I have added buttons that re-order data. To achieve this we need to put the ordering logic inside render rather than inside the d3.csv callback.

<script type="text/javascript">
var data = [];
d3.csv("data.csv",
        function(error, rows) {
            rows.forEach(function(r) {
                data.push({
                    expense: +r.expense,
                    category: r.category
                })
            });
            render();
        });

function render(d3Comparator) {
    if(d3Comparator) data = data.sort(function(a, b) {
        return d3[d3Comparator](a.expense, b.expense);
    });
    d3.select("body").selectAll("div.h-bar") // <-B
            .data(data)
            .enter().append("div")
            .attr("class", "h-bar")
            .append("span");
    d3.select("body").selectAll("div.h-bar") // <-C
            .data(data)
            .exit().remove();
    d3.select("body").selectAll("div.h-bar") // <-D
            .style("width", function(d) {
                return (d.expense * 5) + "px";
            })
            .select("span")
            .text(function(d) {
                return d.category;
            });
}

</script>

<button onclick="render('ascending')">Sort ascending!</button>
<button onclick="render('descending')">Sort descending!</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...