rggplot2geom-col

Separating Stacked Bar Graph Based on Values in a Column


I am having trouble writing the code for a graphical hypothesis. Below I attached the code where I create the data frame then run it in ggplot. I currently get a stacked bar graph which I like but the 0% and 3% salt treatments aggregate when I would like to separate them.Current graph

 library(tidyverse)

    #creating columns
    Strain <- c('Saltgrass', 'Saltgrass','Saltgrass', 'Saltgrass', 'Pickleweed', 'Pickleweed','Pickleweed',     'Pickleweed')
    SaltConcentration <- c(0,0,3,3,0,0,3,3)
    Generation <- c('Generation 1', 'Generation 5', 'Generation 1', 'Generation 5','Generation 1', 'Generation 5', 'Generation 1', 'Generation 5')
    Growth <- c(2,4,1,3,2,4,3,5)

    HypoDF <- data.frame(Strain, SaltConcentration, Generation, Growth)

    #graph dataframe and separate generation, strain, and salt concentration with growth as the y axis

    ggplot(data= HypoDF, mapping = aes(x= Generation, y= Growth, 
       color, fill= Strain, group=SaltConcentration))+
      geom_col()

I tried to mess around with fill, color, and group by adding more arguments to each, but this gave me an error that my aes() length should not go over the given data set. I belive the fix to this code lies somewhere within that line. I also tried adding another geom_col() each with different data -> geom_col(data = HypoDF[which(HypoDF$SaltConcentration==0,]) and geom_col(data = HypoDF[which(HypoDF$SaltConcentration==3,]) but I found this did not create 2 seperate columns next to each other like I was hoping.

Hope you can help, thank you!


Solution

  • Maybe it is a facet what you're looking for?

    library(tidyverse)
    
    #creating columns
    Strain <- c('Saltgrass', 'Saltgrass','Saltgrass', 'Saltgrass', 'Pickleweed', 'Pickleweed','Pickleweed',     'Pickleweed')
    SaltConcentration <- c(0,0,3,3,0,0,3,3)
    Generation <- c('Generation 1', 'Generation 5', 'Generation 1', 'Generation 5','Generation 1', 'Generation 5', 'Generation 1', 'Generation 5')
    Growth <- c(2,4,1,3,2,4,3,5)
    
    HypoDF <- data.frame(Strain, SaltConcentration, Generation, Growth)
    
    #graph dataframe and separate generation, strain, and salt concentration with growth as the y axis
    
    ggplot(data= HypoDF, mapping = aes(x= Generation, y= Growth, 
                                       color, fill= Strain, group=SaltConcentration))+
      geom_col() +
      facet_grid(~SaltConcentration)
    

    Created on 2023-03-02 with reprex v2.0.2