簡體   English   中英

在 ggplot2 中的每個方面注釋組均值

[英]Annotating group means on each facet in ggplot2

我想在 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

在此處輸入圖片說明

遵循另一個問題的示例,我實現了在每個方面標記均值,但現在我得到了額外的樹空網格:library(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

在此處輸入圖片說明

它可以工作的一種方法是使用原始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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM