marioosh
marioosh

Reputation: 28556

Multiple Y axis and paths in different scales

I have data in structure {time, value1, value2}. On axis x (bottom) i have time and i have two axis Y with range of min/max values of value1 and value2. I draw two paths for that values. The problem is that my second path (for value2) is drawn in a fragment on not visible area because of min/max values (.domain, d3.extent) for value1 and value2 are different ([25,130] and [0,65]). How to draw a path for value2 that is assigned to second axis ? I don't want to change a domains. I hope You know what i mean. Code and picture below.

enter image description here

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);

});

Upvotes: 3

Views: 4634

Answers (1)

James Stewart
James Stewart

Reputation: 378

You are creating two y scales, but using the same one for both lines. Define your second line using the second scale like this

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

Upvotes: 3

Related Questions