Skip to content

Grid mark ^0.6.3

The grid mark is a specially-configured rule for drawing an axis-aligned grid. Like the axis mark, a grid mark is automatically generated by Plot when you use the grid scale option. But you can also declare a grid mark explicitly, for example to draw grid lines atop rather than below bars.

ETAOINSHRDLCUMWFGYPBVKJXQZletter024681012frequency (%) →
js
Plot.plot({
  x: {axis: "top", percent: true, grid: !atop},
  marks: [
    Plot.barX(alphabet, {x: "frequency", y: "letter", sort: {y: "width"}}),
    atop ? Plot.gridX({interval: 1, stroke: "white", strokeOpacity: 0.5}) : null,
    Plot.ruleX([0])
  ]
})

The interval option above instructs the grid lines to be drawn at unit intervals, i.e. whole percentages. As an alternative, you can use the ticks option to specify the desired number of ticks or the tickSpacing option to specify the desired separation between adjacent ticks in pixels.

0.00.10.20.30.40.50.60.70.80.91.0
js
Plot.gridX().plot({x: {type: "linear"}})

The color of the grid lines can be controlled with the stroke option (or the alias color). While this option is are typically set to a constant color (such as red or the default currentColor), it can be specified as a channel to assign colors dynamically based on the associated tick value.

0102030405060708090100
js
Plot.gridX(d3.range(101), {stroke: Plot.identity, strokeOpacity: 1}).plot()

You can set other stroke options to further customize the appearance, say for dashed strokes.

0.00.10.20.30.40.50.60.70.80.91.0
js
Plot.gridX({strokeDasharray: "2", strokeOpacity: 1}).plot({x: {type: "linear"}})

See the axis mark for more details and examples.

Grid options

The optional data is an array of tick values — it defaults to the scale’s ticks. The grid mark draws a line for each tick value, across the whole frame.

The following options are supported:

The following options are supported as constant or data-driven channels:

  • stroke - the grid color, defaults to currentColor
  • strokeWidth - the grid’s line width, defaults to 1
  • strokeOpacity - the stroke opacity, defaults to 0.1
  • y1 - the start of the line, a channel of y positions
  • y2 - the end of the line, a channel of y positions

All the other common options are supported when applicable (e.g., title).

gridX(data, options)

js
Plot.gridX({strokeDasharray: "5,3"})

Returns a new x grid with the given options.

gridY(data, options)

js
Plot.gridY({strokeDasharray: "5,3"})

Returns a new y grid with the given options.

gridFx(data, options)

js
Plot.gridFx({strokeDasharray: "5,3"})

Returns a new fx grid with the given options.

gridFy(data, options)

js
Plot.gridFy({strokeDasharray: "5,3"})

Returns a new fy grid with the given options.