如何绘制条形图中单个因子的平均值

How to plot the mean of a single factor in a barplot with

我在使用 ggplot2 创建图形时遇到问题。 在此图中,我使用 geom_bar 绘制三个因素。我的意思是,对于每个 "time" 和 "dose" 我正在绘制两个条形图(两个基因型)。

更具体地说,这就是我的意思:

这是我到目前为止的代码(实际上我更改了一些设置,但我只是展示了需要的内容):

 ggplot(data=data, aes(x=interaction(dose,time), y=b,  fill=factor(genotype)))+
 geom_bar(stat="identity", position="dodge")+
 scale_fill_grey(start=0.3, end=0.6, name="Genotype")

问题:我打算使用点添加每个 time 的平均值,并且这些点正好位于某个 time。我该如何进行?

我尝试使用 geom_dotplot 和 geom_point 添加这些点,但我没有成功。

library(dplyr)
time_data = data %>% group_by(time) %>% summarize(mean(b))
data <- inner_join(data,time_data,by = "time")

这为您提供了附带方法的数据。现在制作情节

 ggplot(data=data, aes(x=interaction(dose,time), y=b,fill=factor(genotype)))+
 geom_bar(stat="identity", position="dodge")+
 scale_fill_grey(start=0.3, end=0.6, name="Genotype")+
 geom_text(aes(b),vjust = 0)

您可能需要 fiddle 在 geom_text 语句中使用参数 hjust 和 vjust。也许 aes 也是,我没有 运行 这个程序所以我不知道。

如果你能给出一个可重现的例子,通常会有帮助。在这里,我做了一些自己的数据。

sampleData <-
  data.frame(
    dose = 1:3
    , time = rep(1:3, each = 3)
    , genotype = rep(c("AA","aa"), each = 9)
    , b = rnorm(18, 20, 5)
  )

你需要在某处计算均值,而我选择即时计算。请注意,我没有使用点,而是使用一条线来显示所有这些值的平均值。我也进行了一些不同的排序,并使用 facet_wrap 将事物聚集在一起。放置点会有点困难,尤其是在使用 position_dodge 时,但您可能会修改此代码来完成此操作。

ggplot(
  sampleData
  , aes(x = dose
        , y = b
        , fill = genotype)
  ) +
  geom_bar(position = "dodge", stat = "identity") +
  geom_hline(data = 
               sampleData %>%
               group_by(time) %>%
               summarise(meanB = mean(b)
                         , dose = NA, genotype = NA)
             , aes(yintercept = meanB)
             , col = "black"
              ) +
  facet_wrap(~time)