简体   繁体   English

条形图多变量(使用 ggplot)

[英]Barplot Multiple Variable (using ggplot)

I want to make a barplot with 2 variables.我想制作一个包含 2 个变量的条形图。

I have a variable called "sexe" and the second is called "surchage_mentale".我有一个名为“sexe”的变量,第二个名为“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.这里不需要pivot。 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())

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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