我想注释ggplot2图形中每个构面组的平均值。 我已经尝试过了:
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(. ~ cyl)
p <- p + annotate("text", label = mean(as.numeric(mtcars$mpg)), size = 4, x = 15, y = 5)
p
按照另一个问题的示例,我实现了在每个方面标注均值,但是现在我得到了额外的树状空网格: 库(ggplot2)
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p <- p + facet_grid(cols=vars(cyl))
ann_text <- data.frame(mpg = c(15, 15, 15),
wt = c(5,5,5),
lab = c(mean(as.numeric(mtcars$mpg[mtcars$cyl==4])),
mean(as.numeric(mtcars$mpg[mtcars$cyl==6])),
mean(as.numeric(mtcars$mpg[mtcars$cyl==8]))),
cyl = c("4","6","8"))
p <- p + geom_text(data=ann_text, label=ann_text$lab)
p
答案 0 :(得分:1)
一种可行的方法是使用原始df中的标签创建一个新col:
mtcars0=mtcars%>%group_by(cyl)%>%mutate(MeanMpg=round(mean(mpg),2))
p <- ggplot(mtcars0, aes(mpg, wt)) + geom_point() + facet_grid(. ~ cyl) +
geom_text(aes(mpg,wt,label=MeanMpg), size = 4, x = 15, y = 5)
p
如果要使用注释,可以通过分别定义标签来完成:
labels<-mtcars%>%group_by(cyl)%>%summarize(MeanMpg=round(mean(mpg),2))%>%.$MeanMpg
p <- ggplot(mtcars0, aes(mpg, wt)) + geom_point() + facet_grid(. ~ cyl) +
annotate("text", label = labels, size = 4, x = 15, y = 5)
p