Search code examples
rggplot2geom-bar

bar chart of row freq ggplot2


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.


Solution

  • 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