rggplot2stackedbarseries

Stacked Barplot using only numerics


I have a data frame which contains 3 columns. First a 'Position', the scond one 'Frac1' as for fraction 1, and finally Frac2" which is the difference between '1 - Frac1'.

I want to make a stacked barplot using 'Position' as 'x', values '0 to 1' as 'y', and for each position there will be a part of 'Frac1' and the rest will be filled with 'Frac2'.

Position <- seq(50)
Frac1 <- runif(50)
Frac2 <- 1-Frac1
A <- data.frame(cbind(Position, Frac1, Frac2))    
barplot(Frac1, ylim=c(0,1), xlab = "POSITION", ylab = "Fraction") 
ggplot() + geom_bar(aes(fill=A$Frac1, y=1, x=A$Position), 
                    data = A, stat="identity")

but the plots do not stacked me both columns.

What I want is something like this

enter image description here


Solution

  • We can reshape to 'long' format and then plot with ggplot

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    A %>%
        pivot_longer(cols = starts_with('Frac'), values_to = 'Fraction') %>%
        ggplot(aes(x = Position, y = Fraction, fill = name)) +
               geom_col()
    

    enter image description here


    Or using gather

    A %>%
        gather(name, Fraction, starts_with('Frac')) %>%
        ggplot(aes(x = Position, y = Fraction, fill = name)) +
               geom_col()
    

    Or in base R

    barplot(`colnames<-`(t(A[-1]), A$Position), legend = TRUE)