Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

r - Annotate outside plot area once in ggplot with facets

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...