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

10

如何使用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()

我很想要发布这张图表的图片,但是我的声望值不够。

我认为 "geom_text" 或 "annotate" 可能会有用,但我不太确定如何使用。


2个回答

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")

现在,如果���真的想要按照这个例子中的 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
  ) 

谢谢。最后一个使用geom_text的示例正是我正在寻找的。我还在逐渐熟悉ggplot2;在ggplot2中是否有一种方法可以使用stat_函数族来进行常见统计计算,而无需先使用dplyr呢? - adatum
另外,我如何在标签的文本部分中包含希腊字母(例如sigma)和/或latex(例如\sigma^2)? - adatum
现在,如何在标签中包含多行以包括平均值和标准差? - adatum
这里似乎\n无法正常工作。对于一个简单的例子,不需要额外的计算:如果parse=T,则paste0("SD: ", hp.sd, "\nVar: ", hp.sd^2)hp.sd之后不会打印任何内容。如果parse=F,则它可以正常工作。 - adatum
1
请移除 my labels 中的空格。 - Julien
显示剩余3条评论

1
我更喜欢当统计数据出现在分面标签中时的图表外观。我制作了以下脚本,允许选择显示标准差、平均值或计数。基本上,它计算汇总统计信息,然后将其与名称合并,使您拥有格式为类别(汇总统计 = 值)的结果。
   #' Function will update the name with the statistic of your choice
AddNameStat <- function(df, category, count_col, stat = c("sd","mean","count"), dp= 0){

  # Create temporary data frame for analysis
  temp <- data.frame(ref = df[[category]], comp = df[[count_col]])

  # Aggregate the variables and calculate statistics
  agg_stats <- plyr::ddply(temp, .(ref), summarize,
                           sd = sd(comp),
                           mean = mean(comp),
                           count = length(comp))

  # Dictionary used to replace stat name with correct symbol for plot
  labelName <- mapvalues(stat, from=c("sd","mean","count"), to=c("\u03C3", "x", "n"))

  # Updates the name based on the selected variable
  agg_stats$join <- paste0(agg_stats$ref, " \n (", labelName," = ",
                           round(agg_stats[[stat]], dp), ")")

  # Map the names
  name_map <- setNames(agg_stats$join, as.factor(agg_stats$ref))
  return(name_map[as.character(df[[category]])])
}

使用这个脚本来回答你的问题:
library(datasets)
data(mtcars)

# Update the variable name
mtcars$cyl  <- AddNameStat(mtcars, "cyl", "hp", stat = "sd")

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

enter image description here

脚本应该易于更改以包含其他摘要统计信息。我也确信它可以在某些部分重写,使其更加清晰!

排版很好,我喜欢。改进可以包括添加单位和允许多个统计数据。 - adatum

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接