Search code examples
rggplot2stacked-chart

How do I create a frequency stacked bar chart however have percentage labels on the bars and frequencies on the y axis, in R?


I started with the code below, however it is not showing the right output. I would just like a normal frequency stacked bar chart to show percentages on the bars but frequencies on the y axis. Could anyone offer any suggestions please?

ggplot(data = df, mapping = aes(x = Family_Size, y = Freq, fill = Survived)) + geom_bar(stat = "identity") + geom_text(aes(label = paste0(df$Percentage),y=Percentage),size = 3) + theme(plot.title = element_text(hjust = 0.5))

<table><tbody><tr><th>Survived</th><th>Family_Size</th><th>Frequency</th><th>Percentage</th></tr><tr><td>Yes</td><td>1</td><td>20</td><td>20%</td></tr><tr><td>No</td><td>1</td><td>80</td><td>80%</td></tr><tr><td>Yes</td><td>2</td><td>40</td><td>40%</td></tr><tr><td>No</td><td>2</td><td>60</td><td>60%</td></tr></tbody></table>


Solution

  • Are you looking for something like that ?

    ggplot(df, aes(x = Family_Size, y = Frequency, fill = Survived))+
      geom_col()+
      scale_y_continuous(breaks = seq(0,100, by = 20))+
      geom_text(aes(label = Percentage), position = position_stack(0.5))
    

    enter image description here


    EDIT: Formatting percentages with two decimales

    ggplot(df, aes(x = Family_Size, y = Frequency, fill = Survived))+
      geom_col()+
      scale_y_continuous(breaks = seq(0,100, by = 20))+
      geom_text(aes(label = paste(format(round(Frequency,2),nsmall = 2),"%")), position = position_stack(0.5))
    

    enter image description here


    Reproducible example

    structure(list(Survived = c("Yes", "No", "Yes", "No"), Family_Size = c(1L, 
    1L, 2L, 2L), Frequency = c(20L, 80L, 40L, 60L), Percentage = c("20%", 
    "80%", "40%", "60%")), row.names = c(NA, -4L), class = c("data.table", 
    "data.frame"))