行频率 ggplot2 的条形图

bar chart of row freq ggplot2

我有以下数据:

dataf <- read.table(text = "index,group,taxa1,taxa2,taxa3,total
                s1,g1,2,5,3,10
                s2,g1,3,4,3,10
                s3,g2,1,2,7,10
                s4,g2,0,4,6,10", header = T, sep = ",")

我正在尝试制作数据频率的堆积条形图,以便它对每个索引 (s1、s2、s3、s4) 跨行(而不是沿列向下)进行计数,然后对每个索引进行计数每个类群的组 (g1,g2)。我只能弄清楚如何绘制一个类群的物种图,而不是所有三个相互堆叠的物种。

以下是我正在尝试制作的一些示例:

这些是在 google 张纸上制作的,因此它们看起来不像 ggplot,但使用 ggplot2 在 r 中制作会更容易,因为真实数据集更大。

##You need to reshape data before doing that.    
 dfm = melt(dataf, id.vars=c("index","group"), 
            measure.vars=c("taxa1","taxa2","taxa3"),
            variable.name="variable", value.name="values")

 ggplot(dfm, aes(x = index, y = values, group = variable)) + 
        geom_col(aes(fill=variable)) +
        theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.25)) +
        geom_text(aes(label = values), position = position_stack(vjust = .5), size = 3) + theme_gray()

您需要重塑数据。

这是我的解决方案(按情节分解)

第一个地块

library(tidyverse)
##For first plot
prepare_data_1 <- dataf %>% select(index, taxa1:taxa3) %>%
  gather(taxa,value, -index) %>%
  mutate(index = str_trim(index)) %>%
  group_by(index) %>% mutate(prop = value/sum(value))


##Plot 1
prepare_data_1 %>%
  ggplot(aes(x = index, y = prop, fill = fct_rev(taxa))) + geom_col()

第二个地块

##For second plot
prepare_data_2 <- dataf %>% select(group, taxa1:taxa3) %>%
  gather(taxa,value, -group) %>%
  mutate(group = str_trim(group)) %>%
  group_by(group) %>% mutate(prop = value/sum(value))

##Plot 2
prepare_data_2 %>%
  ggplot(aes(x = group, y = prop, fill = fct_rev(taxa))) + geom_col()