簡體   English   中英

R中的ggplot2中用於2x2x2設計的堆疊條形圖

[英]Stacked barplot for a 2x2x2 design in ggplot2 in R

我有一個看起來像這樣的數據集:

conifer.abundance <- c(6,7,8,2,3,4,5,1,7,8,9,8,7,6,5,1)
lily.abundance <- c(5,5,5,5,4,4,4,4,6,7,8,2,3,4,5,1)
type <- c("Control","Control","Control","Control","Control","Control","Control","Control","Treatment","Treatment","Treatment","Treatment","Treatment","Treatment","Treatment","Treatment")
class <- c("City","Rural","City","Rural","City","Rural","City","Rural","City","Rural","City","Rural","City","Rural","City","Rural")
climate <- c("wet","wet","dry","dry","wet","wet","dry","dry","wet","wet","dry","dry","wet","wet","dry","dry")
all.abundance <- conifer.abundance + lily.abundance
dat88 <- data.frame(climate,type,class,conifer.abundance, lily.abundance,all.abundance)

這是2x2x2的設計。 我想繪制條形圖,以便將all.abundance的均值表示為mean conifer.abundance和mean lily.abundance(堆疊)的總和,並且它具有自己的傳說。 我嘗試遵循代碼,但是似乎使用fill來堆積條形圖,但是在這里我需要將其用於其他目的。 假設我還有幾個數據點,我還需要繪制一個自舉的置信區間(如下所示)。 有什么建議么? 這是我目前用於繪制上面圖形的代碼。

  pd <- position_dodge(0.82) 
  ggplot(dat88, aes(x=class, y=all.abundance, fill = climate)) + 
  theme_bw() + 
  stat_summary(geom="bar", fun.y=mean, position = "dodge") + 
  stat_summary(geom="errorbar", fun.data=mean_cl_boot,position = pd) + 
  ylab("Total Abundance") + 
  facet_grid(~type)

請注意,我略微更改了數據集以代表更符合生物學的情況。

如果要堆疊女性和男性的身高值,則需要將其融化/收集到單個變量中。

以下兩種用於操縱數據幀的方法是等效的。 取決於您更熟悉哪些軟件包:

# data.table package
dat2 <- data.table::melt(dat, measure.vars = c("male.height", "female.height"),
                         variable.name = "Gender", value.name = "height")

# tidyr package
dat3 <- tidyr::gather(dat, key = Gender, value = height, 
                      male.height, female.height, factor_key = TRUE)

> all.equal(dat2, dat3)
[1] TRUE

由於這是2 x 2 x 2的設計,因此我向facet_grid添加了一個尺寸,以顯示類型和種類。 如果不需要,只需恢復為facet_grid(~type)

ggplot(dat2,
       aes(x = class, y = height, fill = Gender)) +
  geom_col() +
  ylab("Total Height") +
  facet_grid(species~type) +
  scale_fill_discrete(breaks = c("female.height", "male.height"),
                      labels = c("female", "male"))

方面圖

暫無
暫無

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

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