我有一个ggplot facet_grid,我想为每个单独的图添加不同的文本标签。
我已阅读this以映射到一维facet_grid
library(ggplot2)
ann_text <- data.frame(mpg = c(14,15),wt = c(4,5),lab=c("text1","text2"),
cyl = factor(c(6,8),levels = c("4","6","8")))
p <- ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
facet_grid(gear ~ cyl) +
geom_text(data = ann_text,aes(label =lab) )
与ann_text
的匹配如何在geom_text
内工作?
答案 0 :(得分:2)
您需要在cyl
gear
中同时指定ann_text
和 data.frame
,因为这些是您用于分面的变量:
library(ggplot2)
ann_text <- data.frame(mpg = c(14,15),
wt = c(4,5),
lab=c("text1","text2"),
cyl = c(6,8),
gear = 3)
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
facet_grid(gear ~ cyl) +
geom_text(data = ann_text, aes(label = lab))
从那里,很容易得到你正在寻找的东西:
ann_text2 <- data.frame(mpg = 14,
wt = 4,
lab = paste0('text', 1:9),
cyl = rep(c(4, 6, 8), 3),
gear = rep(c(3:5), each = 3))
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
facet_grid(gear ~ cyl) +
geom_text(data = ann_text2, aes(label = lab))