如何根据D3中的y轴刻度绘制水平网格?

时间:2015-11-04 07:16:40

标签: d3.js bar-chart

我很难根据y轴刻度值绘制水平网格。我能够在y轴上绘制网格,但它不是根据Y轴坐标绘制的。

Bar chart

Here is my fiddle     

 // Custom function for text wrap
  function wrap(text, width) {
     text.each(function() {
     var text = d3.select(this),
     words = text.text().split(/\s+/).reverse(),
     word,
     line = [],
     lineNumber = 0,
     lineHeight = 1, // ems
     y = text.attr("y"),
     dy = parseFloat(text.attr("dy")),
     tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
   while (word = words.pop()) {
    line.push(word);
    tspan.text(line.join(" "));
    if (tspan.node().getComputedTextLength() > 55) {
      line.pop();
      tspan.text(line.join(" "));
      line = [word];
      tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
   }
  }
});
}


// The x-accessor for the path generator; xScale ∘ xValue.
function X(d) {
  return xScale(d[0]);
}

function Y0() {
  return yScale(0);
}

// The x-accessor for the path generator; yScale ∘ yValue.
function Y(d) {
 return yScale(d[1]);
}

chart.margin = function(_) {
  if (!arguments.length) return margin;
   margin = _;
   return chart;
 };

  chart.width = function(_) {
   if (!arguments.length) return width;
   width = _;
   return chart;
 };

 chart.height = function(_) {
   if (!arguments.length) return height;
   height = _;
   return chart;
  };

 chart.x = function(_) {
   if (!arguments.length) return xValue;
   xValue = _;
   return chart;
 };

 chart.y = function(_) {
   if (!arguments.length) return yValue;
    yValue = _;
    return chart;
  };

 return chart;
}

}

var table = $('#example').dataTable( {
    "processing": true,
    "serverSide": true,
    "scrollY": 400,
    "scrollX": true,
    scrollCollapse: true,
    fixedColumns:   {
        leftColumns: 3
    },
});

1 个答案:

答案 0 :(得分:0)

你可以做这样的事情

而不是代码生成水平网格

// Horizontal grid
  g.insert("g", ".bars")         
    .attr("class", "grid horizontal")

    .call(d3.svg.axis().scale(yScale)
        .orient("left")
        .tickSize(-(height), 0, 0)
        .tickFormat("")
     );
 });

添加此项将迭代勾选.data(yScale.ticks(5))

    g.append("g").selectAll("line.line").data(yScale.ticks(5)).enter()
.append("line")
    .attr(
    {
        "class":"line grid tick",
        "x1" : margin.right,
        "x2" : width,
        "y1" : function(d){ return yScale(d);},
        "y2" : function(d){ return yScale(d);},
    });
});

工作代码here

相关问题