Search code examples
rggplot2bar-chartfillgeom-bar

Fill geom_bar in ggplot by the percentage in the data frame


I'm trying to create a bar plot where I can fill the bar with one color according to the value of the mean of the first row (0.3181555, which is a percentage) and the rest of the bar with another color (0.6818445, row 2, column 3) to get a bar from 0 to 1. This is my data:

View(int)

   Lower_Conf Upper_Conf   Mean   Lower_Pred Upper_Pred
1  0.3154548  0.3208561 0.3181555  0.3125413  0.3237696
2  0.6845452  0.6791439 0.6818445  0.6874587  0.6762304

My code was like this:

ggplot(int,aes(x=1, y=int[1,3],fill=factor(Mean)))+
  geom_bar(position="fill", stat = "identity", width = 1.2)

And I know is not right cause when I say fill=factor(Mean), it just fills the 50% percent of the bar with one color and the rest with another one, and I know it's because I am filling a bar by "levels" when I have just two (cause there are just 2 numbers in my data). But I don`t know how to fill by the values in my dataframe.


Solution

  • I think this can help you (Also you could filter for specific variable like the mean you want, here I included all the vars in your data):

    library(reshape2)
    library(ggplot2)
    #Data
    df <- structure(list(Lower_Conf = c(0.3154548, 0.6845452), Upper_Conf = c(0.3208561, 
    0.6791439), Mean = c(0.3181555, 0.6818445), Lower_Pred = c(0.3125413, 
    0.6874587), Upper_Pred = c(0.3237696, 0.6762304)), class = "data.frame", row.names = c("1", 
    "2"))
    

    The code:

    #Create id per row
    df$id <- 1:dim(df)[1]
    #Melt
    df.melted <- melt(df,id.vars = 'id')
    df.melted$id <- factor(df.melted$id)
    df.melted$id <- relevel(df.melted$id,ref = '2')
    #Plot
    ggplot(df.melted,aes(x=variable,y=value,fill=id,label=round(value,3)))+
      geom_bar(stat = 'identity')+
      geom_text(position = position_stack(vjust=0.5))+
      scale_fill_manual(values=c('cyan3','tomato'),guide = guide_legend(reverse=TRUE))
    

    Output:

    enter image description here