简体   繁体   中英

Barplot Multiple Variable (using ggplot)

I want to make a barplot with 2 variables.

I have a variable called "sexe" and the second is called "surchage_mentale". And i want this type of graph:

我想要的条形图

But with yes: women/men, and no: women/men

df <- structure(list(sexe = c("women", "men", "women", "men", "women", "men", "women", "men"), surcharge_mentale = c("yes", "yes", "no", "yes", "yes", "no", "yes", "yes")

sexe_surchargementale <- df %>% select(sexe, surcharge_mentale)

#first method
ggplot(sexe_surchargementale, aes(x = "surcharge_mentale", fill = "sexe")) +
    geom_bar(position = "dodge")

#second method
sexe_surchargementale %>%
  pivot_longer(everything(), names_to = "name", values_to = "response") %>%
  group_by(name, response) %>%
  summarise(cnt = n()) %>%
  ggplot(aes(x = name, y = cnt, fill = response)) +
  geom_bar(stat = "identity", position = "dodge") +
  labs(title="") 

I put a sample of my Data. The first method doesn't work and I don't understand why, I'm complety lost.

No need to pivot here. Just use facets, and make sure your variable names are unquoted:

ggplot(sexe_surchargementale, aes(x = surcharge_mentale)) +
  geom_bar(position = "dodge", fill = "deepskyblue3", width = 0.6) +
  facet_grid(.~sexe, switch = "x") +
  theme_light() +
  theme(strip.placement = "outside",
        text = element_text(size = 14),
        strip.background = element_blank(),
        strip.text = element_text(colour = "black", size = 16),
        panel.spacing = unit(0, "mm"),
        panel.border = element_blank(),
        panel.grid.minor.y = element_line(colour = "gray75", size = 0.5),
        panel.grid.major.y = element_line(colour = "gray75", size = 0.5),
        panel.grid.major.x = element_blank())

在此处输入图像描述

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