Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotate outside plot area once in ggplot with facets

Tags:

r

ggplot2

I want to add an annotation outside the plotting area in a faceted ggplot. I can get the annotation that I want, but it's repeated for each facet. How can I get this annotation to appear only once?

E.g., to annotate "XX" once in the top left hand corner I can use:

library("ggplot2")
ggplot(mtcars, aes(x = hp, y = mpg)) +
  geom_point() +
  facet_grid(.~cyl ) + 
  annotate("text", x = -20, y = 36, label = "XX") +
  coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off")

annotated plot

However this actually annotates it to the top left of each facet.

How can I get this to only appear once?

like image 483
Scransom Avatar asked Nov 06 '18 07:11

Scransom


2 Answers

It's in fact very easy, just have a vector of labels, where the ones you don't want to plot are the empty string "".

library("ggplot2")

ggplot(mtcars, aes(x = hp, y = mpg)) +
  geom_point() +
  annotate("text", x = -20, y = 36, label = c("XX", "", "")) +
  facet_grid(.~cyl ) + 
  coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off")

enter image description here

like image 20
Rui Barradas Avatar answered Oct 03 '22 21:10

Rui Barradas


You can put a single tag label on a graph using tag in labs().

ggplot(mtcars, aes(x = hp, y = mpg)) +
     geom_point() +
     facet_grid(.~cyl ) + 
     labs(tag = "XX") +
     coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off")

enter image description here

This defaults to "top left", though, which may not be what you want. You can move it around with the theme element plot.tag.position, either as coordinates (between 0 and 1 to be in plot space) or as a string like "topright".

ggplot(mtcars, aes(x = hp, y = mpg)) +
     geom_point() +
     facet_grid(.~cyl ) + 
     labs(tag = "XX") +
     coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off") +
     theme(plot.tag.position = c(.01, .95))

enter image description here

like image 157
aosmith Avatar answered Oct 03 '22 22:10

aosmith