多组箱线图 + 点 + 计数

Box plot with multiple groups + Dots + Counts

我在 R 中有一个包含多个组的箱线图。

当我在箱线图中添加点时,它们不在中心。 由于每周都有不同数量的箱线图,因此这些点未在箱内居中。

问题出在geom_point部分。 我在文本文件中上传了 df.m 的数据和我得到的数字。

我正在使用 ggplot,这是我的代码:

setwd("/home/usuario")
dput("df.m")
df.m = read.table("df.m.txt")
df.m$variable <- as.factor(df.m$variable)
give.n = function(elita){
return(c(y = median(elita)*-0.1, label = length(elita))) 
    }
p = ggplot(data = df.m, aes(x=variable, y=value))
p = p + geom_boxplot(aes(fill = Label))    
p = p + geom_point(aes(fill = Label), shape = 21, 
         position = position_jitterdodge(jitter.width = 0))
p = p + stat_summary(fun.data = give.n, geom = "text", fun.y = median)
p 

这是我在文本文件中的数据: https://drive.google.com/file/d/1kpMx7Ao01bAol5eUC6BZUiulLBKV_rtH/view?usp=sharing

只有变量12在中间,因为有3组(可能性最大!

我也想展示观察的计数。如果我使用显示的代码,我只能获得所有组的观察次数。我想为每个组添加计数。

提前致谢 enter image description here

这是一个使用 boxplotdotplot 的解决方案以及一个示例数据集:

library(tidyverse)

# example data
dt <- data.frame(week = c(1,1,1,1,1,1,1,1,1,
                          2,2,2,2,2,2,2,2,2),
                  value  = c(6.40,6.75,6.11,6.33,5.50,5.40,5.83,4.57,5.80,
                             6.00,6.11,6.40,7.00,3,5.44,6.00,5,6.00),
                  donor_type = c("A","A","A","A","CB","CB","CB","CB","CB",
                                 "CB","CB","CB","CB","CB","A","A","A","A"))

# create the plot
ggplot(dt, aes(x = factor(week), y = value, fill = donor_type)) +
  geom_boxplot() +
  geom_dotplot(binaxis='y', stackdir='center', position = position_dodge(0.75))

您应该能够轻松地将我的代码调整为您的真实数据集。

使用 OP 数据集编辑的答案:

使用一些生成的数据和geom_point():

library(tidyverse)

df.m <- df.m %>%
  mutate(variable = as.factor(variable)) %>%
  filter(!is.na(value))

ggplot(df.m, aes(x = variable, y = value, fill = Label)) +
  geom_boxplot() +
  geom_point(shape = 21, position = position_jitterdodge(jitter.width = 0)) +
  scale_x_discrete("variable", drop = FALSE)