Christian
Christian

Reputation: 26387

Grid in an R plot

Is there a command to easily add a grid onto an R plot?

Upvotes: 42

Views: 66055

Answers (5)

Quinten
Quinten

Reputation: 41225

Another option is using the axis function for vertical and horizontal grid lines:

x <- rnorm(100)
plot(x)
# Vertical grid
axis(1, tck = 1, lty = 2, col = "gray")
# Horizontal grid  
axis(2, tck = 1, lty = 2, col = "gray")

# Only vertical grid
plot(x)
# Vertical grid
axis(1, tck = 1, lty = 2, col = "gray")

# Only horizontal grid
plot(x)
# Horizontal grid  
axis(2, tck = 1, lty = 2, col = "gray")

Created on 2022-08-20 with reprex v2.0.2

You can specify the position of the grid lines using the at argument.

Upvotes: 3

Tavrock
Tavrock

Reputation: 558

If you are not using a custom tick interval, you can control the grid and axes parameters directly from the plot() command:

plot(cumsum(rnorm(100)), type='l', panel.first=grid())

The plot.default() documentation provides more information about these parameters.

Upvotes: 19

FraNut
FraNut

Reputation: 686

I agree with cbare. Use abline to draw lines only where you really need.

Example from my last code:

abline(v=c(39448, 39814), col="grey40")
abline(h=c(-0.6, -0.4, -0.2, 0.2,0.4,0.6), col="grey10", lty="dotted") 

remember that:

v is for vertical lines. h for horizontal.

exploit the commands

lty for dotted line color for light coloured line

in order to obtain "no heavy grid".

Upvotes: 5

cbare
cbare

Reputation: 12458

The grid command seems to draw grid lines where-ever it feels like. I usually use abline to put lines exactly where I want them. For example,

abline(v=(seq(0,100,25)), col="lightgray", lty="dotted")
abline(h=(seq(0,100,25)), col="lightgray", lty="dotted")

Good luck!

Upvotes: 60

Dirk is no longer here
Dirk is no longer here

Reputation: 368191

See help(grid) which works with standard graphics -- short example:

R> set.seed(42)
R> plot(cumsum(rnorm(100)), type='l')
R> grid()

The ggplot2 package defaults to showing grids due to its 'Grammar of Graphics' philosophy. And lattice has a function panel.grid() you can use in custom panel functions.

By the way, there are search functions for help as e.g. help.search("something") and there is an entire package called sos to make R web searches more fruitful.

Upvotes: 47

Related Questions