Transform dataframe for stacked barplot

Hello everybody,

unfortunately I have to to address this exceptional community again. I want to create a stacked barplot based on the dataset below but I´m struggling how to transform the dataframe appropriately.
Thank you very much in advance for any advice!
data.frame(
stringsAsFactors = FALSE,
check.names = FALSE,
Full time = c(1144,1226,1253,1310,1327,
1144,1226,1253,1310,1327),
Part time = c(186, 176, 1253, 176, 155, 186, 176, 1253, 176, 155),
Year = c("2017","2017","2018","2018",
"2019","2019","2020","2020","2021","2021")
)

Does this do it? Note I edited 2 names in your data.frame to Full_time and Part_time as R does not play well with spaces in variable names.


library(tidyverse)
dat1 <- data.frame(
  stringsAsFactors = FALSE,
  check.names = FALSE,
  Full_time = c(1144,1226,1253,1310,1327,
                1144,1226,1253,1310,1327),
  Part_time = c(186, 176, 1253, 176, 155, 186, 176, 1253, 176, 155),
  Year = c("2017","2017","2018","2018",
           "2019","2019","2020","2020","2021","2021")
)

dat2 <- dat1  %>%  pivot_longer(!Year, names_to = "status", values_to = "hours")

ggplot(dat2, aes(Year, hours, fill = status) ) +
    geom_bar(stat = "identity")

1 Like

Thank you so much @jrkrideau! It works perfectly!!

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.