ggplot stacked bar graph combining 2 data columns

I would like to produce a stacked barplot of my dataframe (df) using tidyr but cannot quite figure out how to transform my dataframe appropriately. I think the answer is to use the melt function in the Reshape2 package but I cannot figure it out. Reproducible example below.

{time <- c("Day", "Day", "Night", "Night", "All", "All")
          a <- c(70, 60, 35, 40, 50, 30)
          b <- c(30, 40, 65, 60, 50, 70)
          df <- data.frame(time, a, b)}

Variables A and B represent time spent in two different behavioral states (all equal to 100%) while Time represents a general qualitative description of when data were collected (day, night, or all times). I would like to transform the data to combine variables A and B into a single column so I can produce a stacked barplot with three bars (day, night, all) of the percent time spent in each behavioral state.

Is this what you are looking for?

time <- c("Day", "Day", "Night", "Night", "All", "All")
   a <- c(70, 60, 35, 40, 50, 30)
   b <- c(30, 40, 65, 60, 50, 70)
   df <- data.frame(time, a, b)

library(tidyr)
df_long <- pivot_longer(df, a:b, names_to = "State", values_to = "Time")  
df_long
# A tibble: 12 x 3
   time  State  Time
   <chr> <chr> <dbl>
 1 Day   a        70
 2 Day   b        30
 3 Day   a        60
 4 Day   b        40
 5 Night a        35
 6 Night b        65
 7 Night a        40
 8 Night b        60
 9 All   a        50
10 All   b        50
11 All   a        30
12 All   b        70
1 Like

Thank you so much--this worked flawlessly!

This topic was automatically closed 7 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.