简体   繁体   中英

ggplot stacked bar graph combining 2 data columns

I would like to produce a stacked barplot of my dataframe (df) using the melt function from the reshape package but cannot quite figure out how to transform my dataframe appropriately. 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.

You can use tidyr to get the data into the right format, then plot it with ggplot .

library(tidyr)
library(ggplot2)

df %>%
  tidyr::pivot_longer(a:b) %>%
  ggplot(aes(fill = name, y = value, x = time)) +
  geom_bar(position = "stack", stat = "identity")

Sample Data

df <- structure(list(
  time = c("Day", "Day", "Night", "Night", "All",
           "All"),
  a = c(70, 60, 35, 40, 50, 30),
  b = c(30, 40, 65, 60,
        50, 70)
),
class = "data.frame",
row.names = c(NA,-6L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM