1

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 :)

Aleksandra
  • 151
  • 8
  • what have you tried so far? Do you have any code? Pleae include the code in the question as well and google "ggplot2 data long to wide and stacked barplot" – Roman May 29 '20 at 12:07
  • it's pivot from wide to long... something like the answer below should be ok. you don't need the whole tidyverse package.. tidyr and ggplot2 are enough – StupidWolf May 29 '20 at 12:10
  • Does this answer your question? [Grouped bar plot in ggplot](https://stackoverflow.com/questions/18158461/grouped-bar-plot-in-ggplot) – UseR10085 May 29 '20 at 12:16
  • Thank You very much for help, the answer below works perfectly. – Aleksandra May 29 '20 at 12:31

1 Answers1

1

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))
Community
  • 1
  • 1
UseR10085
  • 7,120
  • 3
  • 24
  • 54