javascript - 如何为具有多个 y 轴的多线图表中的每一行分配特定 id

标签 javascript d3.js

我试图为具有多个 y 轴的多线图表中的每一行分配一个特定的 id,以便我可以创建一个交互式图例,当单击图例时,该图例可以打开和关闭各行。这是link到我的 fiddle 。

    var xValueArray = [0, 10, 20, 30, 40];
    var arr = [[0, 10, 20, 30, 40], [0, 200, 300, 400, 500]];
    //data array is obtained after structuring arr array
    var data = [[{x: 0, y: 0}, {x: 10, y: 10}, {x: 20, y: 20}, {x: 30, y: 30}, {x: 40, y: 40}], [{x: 0, y: 0}, {x: 10, y: 200}, {x: 20, y: 300}, {x: 30, y: 400}, {x: 40, y: 500}]];

    const margin = {
      left: 20,
      right: 20,
      top: 20,
      bottom: 80
    };

    const svg = d3.select('svg');
    svg.selectAll("*").remove();

    const width = 200 - margin.left - margin.right;
    const height = 200 - margin.top - margin.bottom;

    //const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
    const g = svg.append('g').attr('transform', `translate(${80},${margin.top})`);

    //************* Axes and Gridlines ***************

    const xAxisG = g.append('g');
    const yAxisG = g.append('g');

    xAxisG.append('text')
      .attr('class','axis-label' )
      .attr('x', width / 3)
      .attr('y', -10)
      .style('fill', 'black')
      .text(function(d) {
      return "X Axis";
    });

    yAxisG.append('text')
      .attr('class','axis-label' )
      .attr('id', 'primaryYLabel')
      .attr('x', -height / 2 )
      .attr('y', -15)
      .attr('transform', `rotate(-90)`)
      .style('text-anchor', 'middle')
      .style('fill', 'black')
      .text(function(d) {
      return "Y Axis 1";
    });

    // interpolator for X axis -- inner plot region
    var x = d3.scaleLinear()
    .domain([0, d3.max(xValueArray)])
    .range([0, width])
    .nice();

    var yScale = new Array();
    for (var i = 0; i < 2; i++){
      // interpolator for Y axis -- inner plot region
      var y = d3.scaleLinear()
      .domain([0, d3.max(arr[i])])
      .range([0,height])
      .nice();
      yScale.push(y);
    }

    const xAxis = d3.axisTop()
    .scale(x)
    .ticks(5)
    .tickPadding(2)
    .tickSize(-height)

    const yAxis = d3.axisLeft()
    .scale(yScale[0])
    .ticks(5)
    .tickPadding(2)
    .tickSize(-width);

    yAxisArray = new Array();
    yAxisArray.push(yAxis);
    for (var i = 1; i < 2; i++){
      var yAxisSecondary = d3.axisLeft()
      .scale(yScale[i])
      .ticks(5)
      yAxisArray.push(yAxisSecondary);
    }

    svg.append("g")
      .attr("class", "x axis")
      .attr("transform", `translate(80,${height-80})`)
      .call(xAxis);

    svg.append("g")
      .attr("class", "y axis")
      .attr("transform", "translate(80,20)")
      .call(yAxis);

    var colors = ["blue", "red"];

    //plot lines
    for (var i = 0; i < 2; i++){
      var lineFunction = d3.line()
      .x(function(d) {return x(d.x); })
      .y(function(d) {return yScale[i](d.y); })
      .curve(d3.curveLinear);

      //plot lines
      var paths = g.append("path")
      .attr("class", "path1")
      .attr("id", "blueLine")
      .attr("d", lineFunction(data[i]))
      .attr("stroke", colors[i])
      .attr("stroke-width", 2)
      .attr("fill", "none")
      .attr("clip-path", "url(#clip)")

      //plot a circle at each data point
      g.selectAll(".dot")
        .data(data[i])
        .enter().append("circle")
        .attr("cx", function(d) { return x(d.x)} )
        .attr("cy", function(d) { return yScale[i](d.y); } )
        .attr("r", 3)
        .attr("class", "blackDot")
        .attr("clip-path", "url(#clip)")
    }

    var translation = 50;
    var textTranslation = 0;
    var yLabelArray = ["Y Axis 1", "Y Axis 2"];

    //loop starts from 1 as primary y axis is already plotted
    for (var i = 1; i < 2; i++){
      svg.append("g")
        .attr("transform", "translate(" + translation + "," + 20 + ")")
        .call(yAxisArray[i]);

      yAxisG.append('text')
        .attr('x', -height / 2 )
        .attr('y', -60)
        .attr('transform', `rotate(-90)`)
        .style('text-anchor', 'middle')
        .style('fill', 'black')
        .text(yLabelArray[i]);

      translation -= 40;
      textTranslation += 40;
    }

    //************* Legend ***************
    var legend = svg.selectAll(".legend")
    .data(data)
    .enter().append("g")

    legend.append("rect")
      .attr("x", width + 65)
      .attr("y", 30)
      .attr("width", 18)
      .attr("height", 4)
      .style("fill", "blue")

    legend.append("text")
      .attr("x", width + 60)
      .attr("y", 30)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .on("click", function(){
      // Determine if current line is visible
      var active   = blueLine.active ? false : true,
          newOpacity = active ? 0 : 1;
      // Hide or show the elements
      d3.select("#blueLine").style("opacity", newOpacity);
      // Update whether or not the elements are active
      blueLine.active = active;
    })
      .text(function(d) {
      return "Value1";
    });

    var legend1 = svg.selectAll(".legend")
    .data(data)
    .enter().append("g")

    legend1.append("rect")
      .attr("x", width + 65)
      .attr("y", 50)
      .attr("width", 18)
      .attr("height", 4)
      .style("fill", "red")

    legend1.append("text")
      .attr("x", width + 60)
      .attr("y", 50)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .on("click", function(){
      // Determine if current line is visible
      var active   = blueLine.active ? false : true,
          newOpacity = active ? 0 : 1;
      // Hide or show the elements
      d3.select("#blueLine").style("opacity", newOpacity);
      // Update whether or not the elements are active
      blueLine.active = active;
    })
      .text(function(d) {
      return "Value2";
    });

    var pointLegend = svg.selectAll(".pointLegend")
    .data(data)
    .enter().append("g")

    pointLegend.append("circle")
      .attr("r", 3)
      .attr("cx", width + 70)
      .attr("cy", 70)

    pointLegend.append("text")
      .attr("x", width + 60)
      .attr("y", 70)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .on("click", function(d){
      // Determine if dots are visible
      var active   = d.active ? false : true,
          newOpacity = active ? 0 : 1;
      // Hide or show the elements
      d3.selectAll(".blackDot").style("opacity", newOpacity);
      // Update whether or not the elements are active
      d.active = active;
    })
      .text(function(d) {
      return "Data";
    });

图表可以绘制,这意味着 for 循环可以绘制图表。我正在使用 for 循环,因为我希望根据用户的输入绘制图表,其中我的实际代码中有一个名为 fieldCount 的参数来跟踪用户输入中的系列数,因此我在 for 循环中使用“2”因为为了简化,我的数据数组中只有 2 个数组。

从 fiddle 中,我只能使用可点击的图例切换蓝线,而不能切换红线,因为我为所有线路分配了相同的“blueLine”id。如何将特定的 id 分配给特定的行,以便我可以使用我的图例切换行,并且有没有一种方法可以对图例进行编码,以便我不必声明这么多的图例变量?非常感谢任何帮助!

最佳答案

绘制线条时,您可以将 for 循环的索引 i 传递到 pathid 中,如下所示

//plot lines
var paths = g.append("path")
  .attr("class", "path1")
  .attr("id", "line" + i)

然后,当您执行单击功能时,您可以检查不透明度:

      .on("click", function(d, i) {
        // Determine if current line is visible
        let opacity = d3.select("#line" + i).style("opacity");
        let newOpacity;
        if (opacity == 0) {
            newOpacity = 1;
        }else {
            newOpacity = 0
        }
        d3.select("#line" + i).style("opacity", newOpacity);
      });

此外,在您的代码中,您不必要地绘制了两个图例。我也解决了这个问题。

这是一个解决方案的工作 fiddle : https://jsfiddle.net/7dgek9wq/1/

完整的工作示例如下:

        var xValueArray = [0, 10, 20, 30, 40];
        var arr = [
          [0, 10, 20, 30, 40],
          [0, 200, 300, 400, 500]
        ];
        //data array is obtained after structuring arr array
        var data = [
          [{
            x: 0,
            y: 0
          }, {
            x: 10,
            y: 10
          }, {
            x: 20,
            y: 20
          }, {
            x: 30,
            y: 30
          }, {
            x: 40,
            y: 40
          }],
          [{
            x: 0,
            y: 0
          }, {
            x: 10,
            y: 200
          }, {
            x: 20,
            y: 300
          }, {
            x: 30,
            y: 400
          }, {
            x: 40,
            y: 500
          }]
        ];

        const margin = {
          left: 20,
          right: 20,
          top: 20,
          bottom: 80
        };

        const svg = d3.select('svg');
        svg.selectAll("*").remove();

        const width = 200 - margin.left - margin.right;
        const height = 200 - margin.top - margin.bottom;

        //const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`);
        const g = svg.append('g').attr('transform', `translate(${80},${margin.top})`);

        //************* Axes and Gridlines ***************

        const xAxisG = g.append('g');
        const yAxisG = g.append('g');

        xAxisG.append('text')
          .attr('class', 'axis-label')
          .attr('x', width / 3)
          .attr('y', -10)
          .style('fill', 'black')
          .text(function(d) {
            return "X Axis";
          });

        yAxisG.append('text')
          .attr('class', 'axis-label')
          .attr('id', 'primaryYLabel')
          .attr('x', -height / 2)
          .attr('y', -15)
          .attr('transform', `rotate(-90)`)
          .style('text-anchor', 'middle')
          .style('fill', 'black')
          .text(function(d) {
            return "Y Axis 1";
          });

        // interpolator for X axis -- inner plot region
        var x = d3.scaleLinear()
          .domain([0, d3.max(xValueArray)])
          .range([0, width])
          .nice();

        var yScale = new Array();
        for (var i = 0; i < 2; i++) {
          // interpolator for Y axis -- inner plot region
          var y = d3.scaleLinear()
            .domain([0, d3.max(arr[i])])
            .range([0, height])
            .nice();
          yScale.push(y);
        }

        const xAxis = d3.axisTop()
          .scale(x)
          .ticks(5)
          .tickPadding(2)
          .tickSize(-height)

        const yAxis = d3.axisLeft()
          .scale(yScale[0])
          .ticks(5)
          .tickPadding(2)
          .tickSize(-width);

        yAxisArray = new Array();
        yAxisArray.push(yAxis);
        for (var i = 1; i < 2; i++) {
          var yAxisSecondary = d3.axisLeft()
            .scale(yScale[i])
            .ticks(5)
          yAxisArray.push(yAxisSecondary);
        }

        svg.append("g")
          .attr("class", "x axis")
          .attr("transform", `translate(80,${height-80})`)
          .call(xAxis);

        svg.append("g")
          .attr("class", "y axis")
          .attr("transform", "translate(80,20)")
          .call(yAxis);

        var colors = ["blue", "red"];

        //plot lines
        for (var i = 0; i < 2; i++) {
          var lineFunction = d3.line()
            .x(function(d) {
              return x(d.x);
            })
            .y(function(d) {
              return yScale[i](d.y);
            })
            .curve(d3.curveLinear);

          //plot lines
          var paths = g.append("path")
            .attr("class", "path1")
            .attr("id", "line" + i)
            .attr("d", lineFunction(data[i]))
            .attr("stroke", colors[i])
            .attr("stroke-width", 2)
            .attr("fill", "none")
            .attr("clip-path", "url(#clip)")

          //plot a circle at each data point
          g.selectAll(".dot")
            .data(data[i])
            .enter().append("circle")
            .attr("cx", function(d) {
              return x(d.x)
            })
            .attr("cy", function(d) {
              return yScale[i](d.y);
            })
            .attr("r", 3)
            .attr("class", "blackDot")
            .attr("clip-path", "url(#clip)")
        }

        var translation = 50;
        var textTranslation = 0;
        var yLabelArray = ["Y Axis 1", "Y Axis 2"];

        //loop starts from 1 as primary y axis is already plotted
        for (var i = 1; i < 2; i++) {
          svg.append("g")
            .attr("transform", "translate(" + translation + "," + 20 + ")")
            .call(yAxisArray[i]);

          yAxisG.append('text')
            .attr('x', -height / 2)
            .attr('y', -60)
            .attr('transform', `rotate(-90)`)
            .style('text-anchor', 'middle')
            .style('fill', 'black')
            .text(yLabelArray[i]);

          translation -= 40;
          textTranslation += 40;
        }

        //************* Legend ***************
        var legend = svg.selectAll(".legend")
          .data(data)
          .enter().append("g")

        legend.append("rect")
          .attr("x", width + 65)
          .attr("y", function(d, i) {
            return 30 + i * 20;
          })
          .attr("width", 18)
          .attr("height", 4)
          .style("fill", function(d, i) {
            return colors[i];
          })

        legend.append("text")
          .attr("x", width + 60)
          .attr("y", function(d, i) {
            return 30 + i * 20;
          })
          .attr("dy", ".35em")
          .style("text-anchor", "end")
          .text(function(d, i) {
            return "Value" + (i + 1);
          })
          .on("click", function(d, i) {
            // Determine if current line is visible
            let opacity = d3.select("#line" + i).style("opacity");
            let newOpacity;
            if (opacity == 0) {
            	newOpacity = 1;
            }else {
            	newOpacity = 0
            }
            d3.select("#line" + i).style("opacity", newOpacity);
          });

        var pointLegend = svg.selectAll(".pointLegend")
          .data(data)
          .enter().append("g")

        pointLegend.append("circle")
          .attr("r", 3)
          .attr("cx", width + 70)
          .attr("cy", 70)

        pointLegend.append("text")
          .attr("x", width + 60)
          .attr("y", 70)
          .attr("dy", ".35em")
          .style("text-anchor", "end")
          .on("click", function(d) {
            // Determine if dots are visible
            var active = d.active ? false : true,
              newOpacity = active ? 0 : 1;
            // Hide or show the elements
            d3.selectAll(".blackDot").style("opacity", newOpacity);
            // Update whether or not the elements are active
            d.active = active;
          })
          .text(function(d) {
            return "Data";
          });
.xy_chart {
  position: relative;
  left: 70px;
  top: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
<svg class="xy_chart"></svg>

关于javascript - 如何为具有多个 y 轴的多线图表中的每一行分配特定 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58706745/

相关文章:

javascript - 在 d3.js 圆圈中添加阴影效果

javascript - 如何覆盖 d3.js 图表函数行为?

javascript - 使用 AngularJS 在 2 个不同的指令中调用相同的 $http.get()

javascript - 与 10,000 个对象交互的高性能

javascript - 默认情况下,有人会如何将事件链接内容移动到顶部..

javascript - 如何在 Electron 上加载index.html文件?

javascript - module.exports 函数在另一个文件的 require 之后未定义

javascript - 移动浏览器中的固定地址栏

javascript - ng-select 不适用于渲染数组列表?

javascript - 在 d3.layout.tree() 中自定义单个坐标