如何使用R上的ggplot2在分组条形图上叠加散点图

wgeznvg7  于 2023-05-20  发布在  其他
关注(0)|答案(1)|浏览(141)

我试图创建一个条形图,按主题组和实验条件分组。我想把每个参与者的数据点覆盖在每个条形图的顶部。当我试着把这些点加进去的时候,我能够按缺席/现在的情况对这些点进行排序,而不是按年轻/年长的成年人。有没有一种方法可以将两个变量的点分组,并将它们放在已经分组的条形图的顶部。this is what I have now, but I want the points to be separated into distinct groups by subject group

ACC3 <- read_xls(path="raw_data/ACC3.xls") #loading data file

#setting the order of variables on graphs (from alphabetical to custom)
ACC3$Condition <- factor(ACC3$Condition, c("Absent", "Present")) 
ACC3$Group <- factor(ACC3$Group, c("Young Adult", "Older Adult")) 

ACC3 %>%
    ggplot(aes(fill=Group, y=accuracy, x=Condition)) + 
    geom_bar(position="dodge", width = 0.8, stat = "summary", fun = "mean", color="black", size = .8)+
    facet_grid(cols = vars(Condition), scales = 'free') +
    scale_color_discrete(labels = c("Young Adult", "Older Adult")) +
    stat_summary(fun.data = mean_sdl, geom='errorbar', color='black', position=position_dodge(0.8), width = 0.2, linewidth = 0.8) +
    geom_point(position = position_jitter(0.3), stat="identity", alpha = 0.8)

我也尝试过按主题组而不是条件来做分面,这有助于我将点分类到各自的类别中,但是图形没有按照我想要的方式分组(如第一张图)the dots are grouped correctly, but the bars are not

gopyfrb3

gopyfrb31#

当你想把点和条对齐时,你也可以用position = position_jitterdodge(...)代替position_jitter来避开它们。
使用一些假随机示例数据:

library(ggplot2)

set.seed(123)

ACC3 <- data.frame(
  Condition = sample(c("Absent", "Present"), 100, replace = TRUE),
  Group = sample(c("Young Adult", "Older Adult"), 100, replace = TRUE),
  accuracy = runif(100, 90, 110)
)

ACC3$Condition <- factor(ACC3$Condition, c("Absent", "Present"))
ACC3$Group <- factor(ACC3$Group, c("Young Adult", "Older Adult"))

ggplot(ACC3, aes(fill = Group, y = accuracy, x = Condition)) +
  geom_bar(
    position = "dodge", width = 0.8, stat = "summary", fun = "mean",
    color = "black", linewidth = .8
  ) +
  facet_grid(cols = vars(Condition), scales = "free") +
  scale_color_discrete(labels = c("Young Adult", "Older Adult")) +
  stat_summary(
    fun.data = mean_sdl, geom = "errorbar", color = "black",
    position = position_dodge(0.8), width = 0.2, linewidth = 0.8
  ) +
  geom_point(
    position = position_jitterdodge(0.3, dodge.width = .8),
    alpha = 0.8
  )

相关问题