簡體   English   中英

ggplot2 : 用 geom_bar 繪制均值

[英]ggplot2 : Plot mean with geom_bar

我有以下數據框:

test2 <- data.frame(groups = c(rep("group1",4), rep("group2",4)), 
    X2 = c(rnorm(4), rnorm(4)) , 
    label = c(rep(1,2),rep(2,2),rep(1,2),rep(2,2)))

我正在使用以下方法繪制每組每個標簽的條形圖:

ggplot(test2, aes(label, X2, fill=as.factor(groups))) + 
    geom_bar(position="dodge", stat="identity")

在此處輸入圖片說明

但是,我似乎無法找到stat="mean"以便我可以在每個條形圖上繪制均值而不是標識。

謝謝你的幫助。

只需使用stat = "summary"fun.y = "mean"

ggplot(test2) + 
  geom_bar(aes(label, X2, fill = as.factor(groups)), 
           position = "dodge", stat = "summary", fun.y = "mean")

在此處輸入圖片說明

ggplot2喜歡 1 個數據點為 1 個繪圖點。 使用匯總統計數據創建一個新數據框,然后使用stat="identity"進行繪圖

require(reshape2)
plot.data <- melt(tapply(test2$X2, test2$groups,mean), varnames="group", value.name="mean")

 ggplot(plot.data, aes(x=group,y=mean)) + geom_bar(position="dodge", stat="identity")

在此處輸入圖片說明

嘗試使用ggpubr 它創建類似 ggplot2 的圖表。

library(ggpubr)

ggbarplot(test2, x = "label", y = "X2",
          add = "mean", fill = "groups")

在此處輸入圖片說明

或者,添加一個方面:

ggbarplot(test2, x = "label", y = "X2",
          add = "mean", fill = "groups",
          facet.by = "groups")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM