While gridlines are often frowned upon as chart junk there may be situations where they can assist in data interpretation. With d3 gridlines are easily created using axes and specifying tick sizes to match the chart’s width or height. Here we’ll create a simple x-y plot with gridlines:
To get started we import d3 dependencies and create the main SVG element. Here the SVG is attached to an existing element with an id “grid”:
Next we create our x and y scales and the axes. Two sets of axes are created: xAxis and yAxis to provide the labels and xAxisGrid and yAxisGrid to provide the grids. Note that both axes sets use the same scales:
The grid axes are created on lines 6 and 7. Passing the negative chart height and width to the tickSize functions ensures that the axis lines will span across the chart. Passing an empty string to tickFormat ensures that tick labels aren’t rendered. The ticks function specifies the number of tick marks, here set to 10 to equal the count on the main axes. The last step is to render the axes:
The grids are attached first so they render beneath the main axes. The above will yield black gridlines but they can easily be styled using CSS to match the example at top:
Comments Leave a comment
Leave a comment