Search code examples
rggplot2geom-bargeom-col

How to barplot a column with 2 different variables in only one bar in ggplot


I have this df: estudios_intubacion

  estudio_completo numero
  <chr>             <int>
1 COMPLETO           2838
2 INCOMPLETO          147

And i'm trying to ggplot only one bar/col with the two variables of estudio_completo (COMPLETO and INCOMPLETO) in the x axis and 'n' in the y axis. I have tried with position "stack" and "fill"in many ways but I keep getting two separate bars with no proportions.

grafico_intubacion <- ggplot(estudios_intubacion, 
                         aes (x = estudio_completo, fill = estudio_completo))+
                          geom_bar(position = "stack") +
                        labs(title = "Tasa de intubación cecal",
                               x = "Estudio",
                               y = "Cantidad de estudios",
                             fill = "Estudio" ) +
                        scale_fill_manual(values = c("#C7CEEA", "#FF9AA2"))


Solution

  • Try this

    x <- rep("Estudio",2)
    y <- c(2838,147)
    name <- c("COMPLETO","INCOMPLETO")
    df <- data.frame(x,y,name)
    
    grafico_intubacion <- ggplot(df, aes(x = x, y=y, fill = name)) +
      geom_bar(stat = "identity") + 
      labs(title = "Tasa de intubación cecal",
           x = "Estudio",
           y = "Cantidad de estudios",
           fill = "Estudio" ) +
      scale_fill_manual(values = c("#C7CEEA", "#FF9AA2"))
    
    grafico_intubacion
    

    You will get this output:

    output