How do I uniquely annotate each main facet, but with no annotation in the corresponding margin facets? The following code places the text in the main facets how I'd like, but the margins show the texts superimposed. How do I suppress the text in the margin facets?

frame_labels <- data.frame(
  frame = LETTERS[1:4],
  vs = rep(0:1, each = 2),
  am = rep(0:1, times = 2),
  x = 5, y = 33)

p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p <- p + facet_grid(vs ~ am, margin = TRUE, as.table = FALSE)
p <- p + geom_text(data = frame_labels, aes(x = x, y = y, label = frame))
print(p)
有帮助吗?

解决方案

My take on the thread I mentioned in a comment was that you had to essentially get the "margins" into your dataset. I am sure there is an elegant way to do this, but it is escaping me at the moment. Here is a "brute force" method that seems to work, but isn't pretty.

Essentially I make three extra copies of the dataset and add a third level to vs and am to incorporate the margins. Then I rbind 'em all together. At first I thought it wasn't working, but I realized I needed to change the level order for vs so the reverse order matches the order in your example. Then your dataset frame_labels works like a charm to add the labels.

mtcars2 = mtcars3 = mtcars4 = mtcars
mtcars2$vs = mtcars3$am = mtcars4$am = mtcars4$vs = "all"
mtcarsall = rbind(mtcars, mtcars2, mtcars3, mtcars4)

mtcarsall$vs = factor(mtcarsall$vs, levels = c("all", "0", "1"))

ggplot(mtcarsall, aes(x = wt, y = mpg)) + geom_point() + 
    facet_grid(vs ~ am, as.table = FALSE)+
    geom_text(data = frame_labels, position = NULL, aes(x = x, y = y, label = frame))

其他提示

Simply remove the geom_text(...) part.

Code should look like this to have the desired output

library(ggplot2)

frame_labels <- data.frame(
frame = LETTERS[1:4],
vs = rep(0:1, each = 2),
am = rep(0:1, times = 2),
x = 5, y = 33)

p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p <- p + facet_grid(vs ~ am, margin = TRUE, as.table = FALSE)
print(p)

Hope this helps.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top