Search code examples
rggplot2geom-bar

Make two geom_bar() plots base on different columns in one plot


I have a data frame that looks like this:

 Year     Women       Men
1 2013    145169      889190
2 2014    119064      849778
3 2015    210107     1079592
4 2016    221217     1427639
5 2017    205000     1692592
6 2018    273721     1703456
7 2019    434407     2010493

I want to make a geom_bar, where x is a year and every year has two bars for a number from Women and Men. I have found a solution where this table should looks different, but I'm wondering if there is an option to work with this one. Thank You for any help :)


Solution

  • You can use the following code

    library(tidyverse)
    
    df %>% 
          pivot_longer(cols = -c(Year,Sl), values_to = "Value", names_to = "Name") %>% 
          ggplot(aes(x = Year, y = Value, fill = Name))+geom_col(position = "dodge")
    

    enter image description here

    Data

    df = structure(list(Sl = 1:7, Year = 2013:2019, Women = c(145169L, 
    119064L, 210107L, 221217L, 205000L, 273721L, 434407L), Men = c(889190L, 
    849778L, 1079592L, 1427639L, 1692592L, 1703456L, 2010493L)), class = "data.frame", row.names = c(NA, 
    -7L))