首页 > 解决方案 > 如何在 HTML/D3 代码中对数据进行排序

问题描述

我的问题是如何在下面显示的 HTML/D3 代码中对数据进行排序。我用 Python 编写代码,而 HTML/CSS 对我来说是新的。我有以下代码,我正在准备里面的数据,我该如何对这些数据进行排序。不考虑和不照顾标签。我只想对数据进行排序。我怎样才能做到这一点。非常感谢。我正在学习这个。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3: Sorting visual elements</title>
         <script src="//d3js.org/d3.v5.min.js" charset="utf-8"></script>

    </head>
    <body>
        <script type="text/javascript">

            //Width and height
            var w = 600;
            var h = 250;

            var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
                            11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];

            var xScale = d3.scaleBand()
                            .domain(d3.range(dataset.length))
                            .rangeRound([0, w])
                            .paddingInner(0.05);

            var yScale = d3.scaleLinear()
                            .domain([0, d3.max(dataset)])
                            .range([0, h]);

            //Create SVG element
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);

            //Create bars
            svg.selectAll("rect")
               .data(dataset)
               .enter()
               .append("rect")
               .attr("x", (d,i) => xScale(i) )
               .attr("y", d => h - yScale(d) )
               .attr("width", xScale.bandwidth())
               .attr("height", d => yScale(d) )
               .attr("fill", d => "rgb(0, 0, " + (d * 10) + ")" )

               .on("mouseover", function() {
                    d3.select(this)
                        .attr("fill", "orange");
               })
               .on("mouseout", function(d) {
                   d3.select(this)
                        .transition()
                        .duration(250)
                        .attr("fill", "rgb(0, 0, " + (d * 10) + ")")
               })
               .on("click", () => sortBars() );

            //Create labels
            svg.selectAll("text")
               .data(dataset)
               .enter()
               .append("text")
               .text(d => d)
               .attr("text-anchor", "middle")
               .attr("x", (d, i) => xScale(i) + xScale.bandwidth() / 2)
               .attr("y", d => h - yScale(d) + 14 )
               .attr("font-family", "sans-serif")
               .attr("font-size", "11px")
               .attr("fill", "white");

            //Define sort function
            var sortBars = function() {

                svg.selectAll("rect")
                   .sort((a, b) => d3.ascending(a, b) )
                   .transition()
                   .duration(1000)
                   .attr("x", (d, i) => xScale(i) );
                    };          

        </script>
    </body>
</html>

标签: javascripthtmlcssd3.js

解决方案


推荐阅读