具有多个组+点+计数的箱形图

时间:2018-12-05 18:00:53

标签: r ggplot2 boxplot

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

2 个答案:

答案 0 :(得分:1)

这是使用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))

enter image description here

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

答案 1 :(得分:0)

使用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)

enter image description here

相关问题