如何在水平条形图中移动刻度线标签?

时间:2019-01-27 14:59:55

标签: d3.js

我已经在d3中创建了水平条形图,并且试图实现排序功能来对条形图及其相应标签进行排序。到目前为止的图表如下所示: bar chart

单击“排序”按钮可以正确地对条进行排序,但不会移动标签。

图表数据如下

const data = [
      {
        COL_DIV_CODE: 'Academic Affairs',
        avg_base: 67778.9,
      },
      {
        COL_DIV_CODE: 'Finance and Administration',
        avg_base: 75000.1,
      },
      {
        COL_DIV_CODE: 'Arts and Humanities, College of',
        avg_base: 68109.0,
      },
    ];

到目前为止,这里是代码的完整演示:bl.ocks.org

特别是这部分:

d3.select("#byValue").on("click", function() {
    data.sort(function(a,b) {
        return d3.descending(a.avg_base, b.avg_base);
    });

    yScale.domain(data.map(function(d) {
        return d.avg_base;
    })); 

    // Move bars
    svg.selectAll(".bar")
        .transition()
        .duration(500)
        .attr("y", function(d, i) {
            console.log("bar: ", d.avg_base, " ", yScale(d.avg_base));
            return yScale(d.avg_base);
        });

    // Move bar labels 
    svg.selectAll(".bar-label")
        .transition()
        .duration(500)
        .attr("y", function(d) {
            var obj = findObjectByCollegeName(d, data);
            return yScale(obj.COL_DIV_CODE) + yScale.bandwidth() / 2 - 8;
        });         
});

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

首先,请尝试不要手动更改并非自己创建的节点-即轴标签。通常,正确的方法是选择要应用轴的容器,然后再次在其上使用call(axis)

其次,没有真正的理由让您更改比例的域字段。您这样做需要重新应用它,因为顺序已更改,但是您可以重复使用COL_DIV_CODE。尤为重要,因为axis似乎使用该字段来识别更改前后的标签(call(axis)

一些小事情-在可用时使用attr的替代方法,因为它有时会覆盖所有内容,有时您可能只想更改零件。我正在谈论分配类(使用classed)和样式(styled)。

这是您的bl.ocks代码,只需最少的更改

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
  </style>
</head>

<body>
  <button id="byValue">Sort by Value</button>
  <script>
    const data = [
      {
        COL_DIV_CODE: 'Academic Affairs',
        avg_base: 67778.9,
      },
      {
        COL_DIV_CODE: 'Finance and Administration',
        avg_base: 75000.1,
      },
      {
        COL_DIV_CODE: 'Arts and Humanities, College of',
        avg_base: 68109.0,
      },
    ];

    const maxObj = data.reduce(function(max, obj) {
      return obj.avg_base > max.avg_base? obj : max;
    });

    function findObjectByCollegeName(name, data) {
      for (var i=0;i<data.length;i++) {
        if (data[i].COL_DIV_CODE == name) {
          return data[i]
        }
      }
    }

        const heightMargin = 120;
        const widthMargin = 300;
    const width = 1200 - 2 * widthMargin;
    const height = 400 - 2 * heightMargin;

    var svg = d3.select("body").append("svg")
      .attr("width", 960)
      .attr("height", 500)

    const chart = svg.append('g')
    .attr('transform', `translate(${widthMargin}, ${heightMargin})`);

        // Draw X axis
    const xScale = d3.scaleLinear()
        .range([width, 0])
        .domain([maxObj.avg_base, 0]);

    chart.append('g')
        .attr('transform', `translate(0, 0)`)
        .call(d3.axisTop(xScale));

    // Draw Y axis
    const yScale = d3.scaleBand()
        .range([0, height])
        .domain(data.map((s) => s.COL_DIV_CODE))
        .padding(0.2);

    var axisLeft = d3.axisLeft(yScale).tickFormat(function(d) {return d; });

    chart.append('g')
        .attr('transform', `translate(0, 0)`)
        .attr('class', 'y-axis')
        .call(axisLeft);

    d3.selectAll(".y-axis .tick text")
      .attr("class", "bar-label"); // Add a class to the bar labels 

    // Draw gridlines - vertical
    chart.append('g')
        .attr('class', 'grid')
        .call(d3.axisTop()
            .scale(xScale)
            .tickSize(-height, 0, 0)
            .tickFormat(''));

    // // Draw bars
    chart.selectAll()
        .data(data)
        .enter()
        .append('rect')
        .attr("class","bar")
        .attr('style', 'fill: steelblue')
        .attr('y', (s) => yScale(s.COL_DIV_CODE))
        .attr('x', 0)
        .attr('width', (s) => xScale(s.avg_base))
        .attr('height', yScale.bandwidth());

     d3.select("#byValue").on("click", function() {
      data.sort(function(a,b) {
        return d3.descending(a.avg_base, b.avg_base);
      });

        yScale.domain(data.map(function(d) {
        return d.COL_DIV_CODE;
    })); 

    // Move bars
        svg.selectAll(".bar")
            .transition()
            .duration(500)
            .attr("y", function(d, i) {
                console.log("bar: ", d.avg_base, " ", yScale(d.avg_base));
                return yScale(d.COL_DIV_CODE);
            });

    // Move bar labels 
       /*
        svg.selectAll(".bar-label")
            .transition()
            .duration(500)
            .attr("y", function(d) {
                var obj = findObjectByCollegeName(d, data);
                return yScale(obj.COL_DIV_CODE) + yScale.bandwidth() / 2 - 8;
            });     
        */

         chart.select('g.y-axis')
            .transition()
                    .duration(500)
            .call(axisLeft);

    });
  </script>
</body>