Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Grid to D3.js Line Chart

I have this Line Chart here:

jsfiddle.net/yfqQ4/

My Problem now is, that I don't get a proper grid in the background working with a legend (y and x-Axis) like this: http://lab.creativebrains.net/linechart.png

Can anybody can post me a code snippet how I should implement it or something like that?

Thanks!

like image 762
mrks Avatar asked Jun 18 '26 15:06

mrks


1 Answers

I would suggest to use d3.svg.axis().scale() to tie up the grid to your coordinates. I drew a quick example based on your code: http://jsfiddle.net/yfqQ4/5/

enter image description here

The gist is to use the existing scales, x and y, and to use ticks as grid. Notice that height and width are the variable defining the size of your container. Here is the relevant code:

var numberOfTicks = 6;

var yAxisGrid = d3.svg.axis().scale(y)
  .ticks(numberOfTicks) 
  .tickSize(width, 0)
  .tickFormat("")
  .orient("right");

var xAxisGrid = d3.svg.axis().scale(x)
  .ticks(numberOfTicks) 
  .tickSize(-height, 0)
  .tickFormat("")
  .orient("top");

svg.append("g")
  .classed('y', true)
  .classed('axis', true)
  .call(yAxisGrid);

svg.append("g")
  .classed('x', true)
  .classed('axis', true)
  .call(xAxisGrid);
like image 84
Vadym Tyemirov Avatar answered Jun 21 '26 03:06

Vadym Tyemirov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!