【问题标题】:D3 Bar Graph: flipping the Y-axis flips my dataD3条形图:翻转Y轴翻转我的数据
【发布时间】:2019-07-21 09:10:36
【问题描述】:

我在 d3 中制作条形图时遇到了一个常见问题:我的 y 轴颠倒了。经过一番谷歌搜索,我发现解决此问题的最佳方法是反转 y 域。唯一的问题是,当我这样做时,我的图表上的条形图切换了位置,所以最大的是在开头而不是结尾。我需要 y 轴正确,而不改变我的条形。

条形图位置正确,但 y 轴倒置

条形不正确,但 y 轴朝上

这里是代码:https://codepen.io/lucassorenson/pen/rPRadR?editors=0010

const yScale = d3.scaleLinear()
  .domain([0, d3.max(json, (d) => d[1])])
  .range([h - padding, padding]);
const yAxis = d3.axisLeft(yScale);

这是我更改的代码。如果反转范围([padding, h - padding]),条形图正确,但轴不正确。

【问题讨论】:

    标签: javascript d3.js axes


    【解决方案1】:

    解决方法是简单地交换属性“height”和“y”的回调函数。

    您的代码是:

    ...
    svg.selectAll('rect')
        .data(json)
        .enter()
        .append('rect')
        .attr('width', 3)
        .attr('height', (d) => yScale(d[1]))
        .attr('x', function(d, i){
          return i*4 + padding
        })
        .attr('y', function(d){
          return  h - yScale(d[1]) - padding
        })
    

    改成:

    ...
    svg.selectAll('rect')
        .data(json)
        .enter()
        .append('rect')
        .attr('width', 3)
        .attr('y', (d) => yScale(d[1]))
        .attr('x', function(d, i){
          return i*4 + padding
        })
        .attr('height', function(d){
          return  h - yScale(d[1]) - padding
        })
    

    使用属性“y”通常设置矩形的上边缘,使用“高度”表示它下降的距离。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      • 2017-12-07
      • 2021-02-13
      • 2014-07-07
      • 1970-01-01
      • 2014-06-23
      • 1970-01-01
      相关资源
      最近更新 更多