Camila Vargas Restrepo
Camila Vargas Restrepo

Reputation: 409

Annotate the axis ggplo2

I am trying to create an annotation (particularly a rectangle) over a ggplot. Here's what I want to get: highlighted axis

I have tried geom_rect but that can only draw inside the plot axis. I have also attempted to use annotate_custom which this post mentions, but when I try to work with xmin = -3 (for instance), it doesn't work.

Thank you!

Upvotes: 0

Views: 118

Answers (1)

MrGumble
MrGumble

Reputation: 5766

I'm gonna start by asking what you are trying to achieve with this? It seems odd, at least in your example.

But, it can be done. Because you did not provide a reproducible example, I've got something else. The goal here is to turn of the panel's clipping, such that elements that lie outside it's boundaries will be plotted.

library(ggplot2)
library(grid)

# Create a plot
p <- ggplot(mtcars, aes(wt, mpg)) + geom_point()

Here, I'm adding a rectangle with rect. But this also modifies the x- and y-axis, so we fix these with coord_cartesian. You cannot use xlim as this will remove data points that fall outside the range.

g <- p +  annotate('rect', xmin=-1, xmax=3, ymin=10, ymax=30, fill='blue', alpha=1/3) +
  coord_cartesian(xlim=c(1, 4))

# Convert into a graphical object -- a grob
g <- ggplotGrob(g)

# Try printing g

g is an object that puts all the elements into a table-like structure. So now, we find the panel in the layout dataframe of g, and turn of clipping.

i <- which(g$layout$name == 'panel')
g$layout[i,'clip'] <- 'off'

Finally draw the grob:

# grid.newpage()
grid.draw(g)

enter image description here

Upvotes: 2

Related Questions