Grid in an R Plot

Grid line consistent with ticks on axis

From ?grid description of the nx and ny arguments:

When NULL, as per default, the grid aligns with the tick marks on the
corresponding default axis (i.e., tickmarks as computed by axTicks)

plot (x = 1:10, y = rnorm (10, 5, 2)) 
grid (NULL,NULL, lty = 6, col = "cornsilk2")

Align grid() to plot ticks

You could use abline to draw grids. You can specify where the grids should be with h (for horizontal lines) and v (for vertical lines)

#Plot
plot(1:10,las=1,xaxp = c(0, 10, 10),xlim=c(0,10), ylim=c(0,10))
#Add horizontal grid
abline(h = c(0,2,4,6,8,10), lty = 2, col = "grey")
#Add vertical grid
abline(v = 1:10, lty = 2, col = "grey")

Another workaround is to use axis where tck value is 1. With axis, you can specify where the grids should be with at

#Plot
plot(1:10,las=1,xaxp = c(0, 10, 10),xlim=c(0,10), ylim=c(0,10))

#Add horizontal grid
axis(2, at = c(0,2,4,6,8,10), tck = 1, lty = 2, col = "grey", labels = NA)

#Add vertical grid
axis(1, at = 1:10, tck = 1, lty = 2, col = "grey", labels = NA)

#Add box around plot
box()

Sample Image

R language: plot grid lines only inside the graph

When I have had this problem it is because par(xpd=TRUE) is somewhere in the code. Try setting par(xpd=FALSE) before using grid() and then par(xpd=TRUE). The sample code was used to generate the same the two plots, one of which has the grid lines extending outside of the plot region.

Sample Image

Sample Image

set.seed(1)
x <- rnorm(100)
y <- rnorm(100)

# scatter plot with gridlines inside
par(xpd=FALSE) # do not plot outside the plot region
plot(x,y)
grid(lwd=2)

# scatterplot with gridlines outside the region
par(xpd=TRUE) # plot outside the plot region
plot(x,y)
grid(lwd=2)

Plotting a grid behind data, not in front in R

This is relatively easy.

Generate the histogram but don't plot it.

h <- hist(y, plot = FALSE)

Now generate your base plot... I've added some features to make it look more like a standard historgram

plot(h$mids, h$counts, ylim = c(0, max(h$counts)), xlim = range(h$mids)*1.1, 
type = 'n', bty = 'n', xlab = 'y', ylab = 'Counts', main = 'Histogram of y')

add your grid

grid()

add your histogram

hist(y, add = TRUE)

Or, as I discovered through this process... you can do it even easier

hist(y)
grid()
hist(y, add = TRUE, col = 'white')

This last method is just redrawing the histogram over the grid.

Grid in an R plot

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.

Grid in the back of boxplot in R

Probably not he most elegant way, but you can draw first a boxplot without color border, axis labeling and frame, add your grid and then add boxplot over by using the argument add = TRUE:

boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders",
ylab = "Miles Per Gallon", border = NA,
xaxt='n', yaxt = "n", frame = FALSE)
grid(nx=16, ny=16)
boxplot(mpg ~ cyl, data = mtcars, xlab = "Number of Cylinders",
ylab = "Miles Per Gallon", add = TRUE, ann = FALSE)

Sample Image

Does it answer your question ?

Plot with a grid

How about heatmap?

m=matrix(runif(12),3,4)
rownames(m)=c("Me","You","Him")
colnames(m)=c("We","Us","Them","I")
heatmap(m,NA,NA)

Sample Image

Note that it works on a matrix and not a data frame because all the values have to be numbers, and data frames are row-oriented records.

See the help for other options.

Defining grid.arrange() so the third plot is in the middle?

No idea about gridExtra, but since you said alternatives are OK, it's really straightforward with patchwork :)

library(ggplot2)
library(patchwork)

P1 <- ggplot(mtcars, aes(x = mpg)) +
geom_histogram()

P2 <- ggplot(mtcars, aes(x = wt)) +
geom_histogram()

P3 <- ggplot(mtcars, aes(x = qsec)) +
geom_histogram()

(P1 + P2) / P3

plot with only horizontal gridlines and labels

The documentation of ?grid gives a solution to this problem. From section Note.

Note

If more fine tuning is required, use abline(h = ., v = .) directly.

old_par <- par(xpd = TRUE, mai=c(0.5,1,0.5,0.2)) 

barplot(1:3, axes = FALSE)
abline(h = 1:3, col = "grey", lty = "dotted")
barplot(1:3, axes = FALSE, add = TRUE)
text(x = -0.5, y = 1:3, labels = 1:3)

par(old_par)

Sample Image

To have the y axis labels at the end of the grid lines and to place them automatically, a function can be defined.

segmText <- function(x0, x1, y, ...){
segments(x0 = x0, x1 = x1,
y0 = y, y1 = y, ...)
text(x = x0, y = y, labels = y)

}

old_par <- par(xpd = TRUE, mai = c(0.5,1,0.5,0.2)) # to extend lines to the left of plotting area
barplot(1:3, axes = FALSE)
segmText(x0 = -0.5, x1 = 4, y = 1:3, col = "grey", lty = "dotted")
barplot(1:3, axes = FALSE, add = TRUE)
par(old_par)

Edit

A simpler solution seems to be in the comment by user d.b

graphics.off()
barplot(1:3, axes = FALSE, col = NA, border = NA)
abline(h = 1:3, col = "grey", lty = "dotted")
barplot(1:3, axes = FALSE, add = TRUE)
axis(2, at = 1:3, labels = 1:3, las = 2, col = NA)


Related Topics



Leave a reply



Submit