Schillerlocke
Schillerlocke

Reputation: 343

ggplot and pivot_longer on multiple factors

I want to make my data frame longer, so I can make a plot out of it. I have a dichotomous variable (sex) by which I want to sort. And I have four exposures as factors.

  DF <- data.frame(sex = rbinom(1000, 1, .5),
                                expo_1 = rbinom(1000, 1:4, .15),
                                expo_2 = rbinom(1000, 1:4, .25),
                                expo_3 = rbinom(1000, 1:4, .3),
                                expo_4 = rbinom(1000, 1:4, .45))                                                   
  DF$sex <- as.factor(sex)
  DF$expo_1 <- as.factor(expo_1)
  DF$expo_2 <- as.factor(expo_2)
  DF$expo_3 <- as.factor(expo_3)
  DF$expo_4 <- as.factor(expo_4)

This is as far as I got. I'm struggling to get a count for each level of an expo.

DF %>%
  pivot_longer(cols = -sex, names_to = "expo") %>%
  group_by(sex, expo) 

And I would like to have something like this:

enter image description here

Help is much appreciated and thanks in advance!

Upvotes: 2

Views: 2392

Answers (1)

tjebo
tjebo

Reputation: 23737

You were almost there - use facets and geom_bar for raw count of value as fill aesthetic. Stacked position by default.

Tip: use mutate_all for easier type conversion

library(tidyverse)
DF <- data.frame(sex = rbinom(1000, 1, .5),
                 expo_1 = rbinom(1000, 1:4, .15),
                 expo_2 = rbinom(1000, 1:4, .25),
                 expo_3 = rbinom(1000, 1:4, .3),
                 expo_4 = rbinom(1000, 1:4, .45))   

DF <- DF %>% mutate_all(as.factor)

df_long <- DF %>%
  pivot_longer(cols = -sex, names_to = "expo")

ggplot(df_long) + geom_bar(aes(x = expo, fill = value)) +facet_grid(~sex)

Created on 2020-03-23 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions