Reputation: 19
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.
Upvotes: 1
Views: 190
Reputation: 173793
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())
Upvotes: 3