user2911296
user2911296

Reputation:

ggplot2: Add diagonals to grid

Is it possible to tweak ggplot2 in a way that it adds diagonals to the grid?

Obviously, the default grid consists of vertical and horizontal lines:

df <- data.frame(a = sample(0:100, 100, T), b = sample(0:100, 100, T))
gg <- ggplot() + geom_point(data = df, aes(x = a, y = b))
gg

plot1

What I'm thinking about is to modify the default behaviour to achieve a grid that consists of vertical, horizontal and diagonal lines. A quite messy way to achieve this is to use segments:

d <- data.frame(x = c(0,0,0,0,25,50,75),
                y = c(75,50,25,0,0,0,0),
                xend = c(25,50,75,100,100,100,100),
                yend = c(100,100,100,100,75,50,25))


gg + 
  geom_segment(data = d, aes(x = x, y = y, xend = xend, yend = yend), colour = "white")

plot2

This seems to be a workaround. But the actual number of segments needed depends on the range of the data. While one could write a function to calculate the number of segments considering the desired spaces between the diagonals, ggplot2 will nevertheless treat this 'workaround data' as actual data. This is what I want to avoid.

Upvotes: 4

Views: 715

Answers (1)

Weihuang Wong
Weihuang Wong

Reputation: 13118

How about geom_abline?

gg + geom_abline(intercept=seq(-100, 100, 25),
                 slope=1,
                 colour="white")

enter image description here

Upvotes: 6

Related Questions