R:ggplot2,如何在面板图的每个面板上注释摘要统计

ada*_*tum 9 r ggplot2

如何使用R中的ggplot2在以下图表的每个面板中添加标准偏差的文本注释(例如,sd = sd_value)?

library(datasets)
data(mtcars)
ggplot(data = mtcars, aes(x = hp)) + 
        geom_dotplot(binwidth = 1) + 
        geom_density() + 
        facet_grid(. ~ cyl) + 
        theme_bw()
Run Code Online (Sandbox Code Playgroud)

我发布了一个情节图片,但我没有足够的代表.

我认为"geom_text"或"annotate"可能有用,但我不确定如何.

Jas*_*lns 4

如果您想改变每个方面的文本标签,您将需要使用geom_text. 如果您希望每个方面都显示相同的文本,则可以使用annotate

p <- ggplot(data = mtcars, aes(x = hp)) + 
  geom_dotplot(binwidth = 1) + 
  geom_density() + 
  facet_grid(. ~ cyl)

mylabels <- data.frame(
  cyl = c(4, 6, 8), 
  label = c("first label", "second label different", "and another")
)

p + geom_text(x = 200, y = 0.75, aes(label = label), data = mylabels)

### compare that to this way with annotate

p + annotate("text", x = 200, y = 0.75, label = "same label everywhere")
Run Code Online (Sandbox Code Playgroud)

现在,如果您确实想要cyl此示例中的标准差,我可能会dplyr先进行计算,然后geom_text像这样完成:

library(ggplot2)
library(dplyr)
    
df.sd.hp <- mtcars %>%
  group_by(cyl) %>%
  summarise(hp.sd = round(sd(hp), 2))
    
ggplot(data = mtcars, aes(x = hp)) + 
  geom_dotplot(binwidth = 1) + 
  geom_density() + 
  facet_grid(. ~ cyl) +
  geom_text(
    data = df.sd.hp, 
    aes(label = paste0("SD: ", hp.sd))
    x = 200, y = 0.75
  ) 
Run Code Online (Sandbox Code Playgroud)