0

I have multiple exposures in multiple variables that are coded with 0 and 1. Not-exposed and exposed. Those are not exclusive with each other. I want to put each in one graphic side by side on the x-axis in a gg bar plot but I am struggling.

sex <- rbinom(1000, 1, .5)
expo_1 <- rbinom(1000, 1, .05)
expo_2 <- rbinom(1000, 1, .1)
expo_3 <- rbinom(1000, 1, .15)
expo_4 <- rbinom(1000, 1, .2)
DF <- data.frame(sex, expo_1, expo_2, expo_3, expo_4)

DF$sex <- as.factor(DF$sex)

First I thought about merging them in a new variable as a categorical variable with each exposure as a new level but I think now that makes little sense and introduced errors.

DF$expo_sum <- 0
DF$expo_sum[DF$expo_1 == 1] <-  1
DF$expo_sum[DF$expo_2 == 1] <-  2
DF$expo_sum[DF$expo_3 == 1] <-  3
DF$expo_sum[DF$expo_4 == 1] <-  4

This way it didn't work.

What I want is this:

ggplot(DF, aes(x = expo_1, fill = sex))+
  geom_bar(position = "dodge")

but also with expo_2, expo_3 and expo_4 on the same axis. Like "x = c(expo_1, expo_2, expo_3 and expo_4)" Why isn't this a valid code in ggplot!

Anyone knows how to do so? Thanks in advance!

1 Answer 1

4

I think this is what you want (hard to know for sure)... Usually, when you have multiple variables in wide form, you have to reshape it to long form because ggplot prefers this.

library(tidyr)
library(dplyr)

DF %>%
  pivot_longer(cols=-sex, names_to="expo") %>%
  group_by(sex, expo) %>%
  summarise(value=sum(value)) %>%
  ggplot(aes(x = expo, y=value, fill = sex)) +
  geom_bar(position = "dodge", stat="identity")

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.