2
votes

I have the following data:

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 = ",")

I'm trying to make a stacked bar plot of the frequences of the data so that it counts across the row (not down a column) for each index (s1,s2,s3,s4) and then for each group (g1,g2) of each taxa. I'm only able to figure out how to graph the species of one taxa but not all three stacked on each other.

Here are some examples of what I'm trying to make:

enter image description here

enter image description here

These were made on google sheets so they don't look like ggplot but it would be easier to make in r with ggplot2 because the real data set is larger.

2

2 Answers

3
votes

You would need to reshape the data.

Here is my solution (broken down by plot)

For first plot

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()

enter image description here

For second plot

##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()

enter image description here

1
votes
##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()