简体   繁体   中英

ggplot how to plot multiple variables on the x axis

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!

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")

在此处输入图片说明

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