【问题标题】:Label a Boxplot with number of subgroups and observations per box用每个盒子的子组数和观察值标记箱线图
【发布时间】:2020-02-12 03:48:29
【问题描述】:

我想制作一个箱线图,在其中我用与该框相关的观察数以及与该框相关的子组数标记每个框

使用 ggplot2 包中包含的 diamonds 数据集,我可以通过以下代码接近我想要的结果

data("diamonds")
n_fun <- function(x){
  return(data.frame(y = 1,
                    label = length(x)))
}
ggplot(diamonds, aes(x=cut, y=price, fill=clarity)) +
  geom_boxplot(position = position_dodge2(width=0.75, preserve='single')) + 
  theme_bw() + 
  stat_summary(fun.data = n_fun, geom = "text",aes(group=clarity),hjust = 0.5, position = position_dodge(0.6))

这给了我一个图,它显示每个“框”的观察次数 我想做的是既显示观察次数,又显示每个框中的颜色数,例如

Fair_I1<-subset(diamonds, cut=="Fair" & clarity=="I1")
table(Fair_I1$color)

表明在与 Fair-I1 相关的框中存在 7 个颜色组

因此,最后一个示例将在图中的此框下方或上方同时显示 7(颜色数)和 210(观察数)

【问题讨论】:

    标签: r ggplot2 boxplot


    【解决方案1】:

    您可以预先汇总数据并将汇总数据传递给geom_text()。在这里,我将值折叠到一个标签中,但如果您希望一组数字位于顶部,另一组位于底部,您可以独立完成它们并放置单独的层。

    library(ggplot2)
    library(dplyr)
    
    labeldat <- diamonds %>%
      group_by(cut, clarity) %>%
      summarise(labels = paste(n(), n_distinct(color), sep = "\n"))
    
    ggplot(diamonds, aes(x=cut, y=price, fill=clarity)) +
      geom_boxplot(position = position_dodge2(width=0.75)) + 
      theme_bw() + 
      geom_text(data = labeldat, aes(x = cut, y = -250, label = labels), hjust = 0.5, position = position_dodge2(width = .75))
    

    【讨论】:

      猜你喜欢
      • 2020-12-08
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 2020-10-07
      • 2016-03-27
      • 2015-01-30
      相关资源
      最近更新 更多