1

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 :

The barplot I want

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.

3
  • Your data is fine, you do not need to "pivot" it. Also, you do not need quotation marks, try: aes(x = surcharge_mentale, fill = sexe) instead of aes(x = "surcharge_mentale", fill = "sexe"). Commented Apr 18, 2022 at 11:34
  • it doesn't work I only have one bar called "surcharge_mentale" and fill it's just "sexe" Commented Apr 18, 2022 at 12:06
  • Are you sure you tried the command without the quotation marks? (") Commented Apr 18, 2022 at 12:26

1 Answer 1

3

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

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.