如何对每个主要方面进行唯一注释,但在相应的边缘方面没有注释?下面的代码将文本放在主要方面我的方式,但边距显示叠加的文本。如何抑制边缘刻面中的文本?
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)
答案 0 :(得分:0)
我对the thread I mentioned in a comment的看法是你必须在数据集中获得“边距”。我确信有一种优雅的方式可以做到这一点,但它现在正在逃避我。这是一种似乎有效的“蛮力”方法,但并不漂亮。
基本上,我会为数据集制作三个额外的副本,并将第三个级别添加到vs
和am
以合并边距。然后我rbind
'他们在一起。起初我认为它不起作用,但我意识到我需要更改vs
的级别顺序,因此相反的顺序与示例中的顺序相匹配。然后,您的数据集frame_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))
答案 1 :(得分:0)
只需删除geom_text(...)部分。
代码应如下所示,以获得所需的输出
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)
希望这有帮助。