我在结构 {time, value1, value2} 中有数据。在 x 轴(底部)上,我有 time ,我有两个 Y 轴,其最小值/最大值范围为 value1value2 。我为该值绘制了两条路径。问题是,由于 value2.domain 的最小值/最大值( d3.extentvalue1 )不同([25,130] 和 [0,65]),我的第二条路径(对于 value2 )被绘制在不可见区域的片段中。如何为分配给第二个轴的 value2 绘制路径?我不想更改域。我希望你知道我的意思。代码和图片如下。

var x = d3.time.scale()
    .range([0, width]);
var y = d3.scale.linear()
    .range([height, 0]);
var y2 = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");
var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");
var yAxis2 = d3.svg.axis()
    .scale(y2)
    .orient("left");

var line = d3.svg.line()
    .x(function(d) { return x(d.time); })
    .y(function(d) { return y(d.value1); });

var line2 = d3.svg.line()
    .x(function(d) { return x(d.time); })
    .y(function(d) { return y(d.value2); });

d3.json('/data.json', function(error, data){

      x.domain(d3.extent(data, function(d) { return d.time; }));
      y.domain(d3.extent(data, function(d) { return d.value1; })); // [25, 130]
      y2.domain(d3.extent(data, function(d) { return d.value2; })); // [0, 65]


      svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis);

      svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Value1");

      svg.append("g")
          .attr("class", "y2 axis")
          .attr("transform", "translate(-40,0)") // second axis a little to the left
          .call(yAxis2)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Value2");

      /**
       * datum ?
       */
      svg.append("path")
          .datum(data)
          .attr("class", "line")
          .attr("d", line);

      svg.append("path")
          .datum(data)
          .attr("class", "line2")
          .attr("d", line2);

});

最佳答案

您正在创建两个 y 比例,但对两条线使用相同的比例。像这样使用第二个比例定义你的第二行
var line2 = d3.svg.line() .x(function(d) { return x(d.time); }) .y(function(d) { return y2(d.value2); });

关于d3.js - 多个 Y 轴和不同比例的路径,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24519098/

10-12 17:38