Am trying to do a graph but want to order the factor variable based on given values. It seems the plot does not mirror what I want. I would the languages be ordered based on the meanscore. Any ideas?
library(tidyverse)
set.seed(200) # reproducibility
df <- tibble(
language = gl(4, 10, labels = c("Python", "R", "Javascipt", "Excel")),
gender = factor(ifelse(sign(rnorm(40))==-1, 0, 1), labels = c("Male", "Female")),
score = floor(runif(40, 25, 80))
)
df <- df %>% group_by(gender, language) %>%
summarise(meanscore = mean(score))
df %>%
mutate(language = fct_reorder(language, meanscore)) %>%
ggplot(aes(language, meanscore, fill = gender))
geom_col()
facet_wrap(~gender)
coord_flip()
CodePudding user response:
I believe this is what you want? Utilizing the reorder_within from the package tidytext.
library(tidytext)
set.seed(200)
df <- tibble(
language = gl(4, 10, labels = c("Python", "R", "Javascipt", "Excel")),
gender = factor(ifelse(sign(rnorm(40))==-1, 0, 1), labels = c("Male", "Female")),
score = floor(runif(40, 25, 80))
)
df <- df %>% group_by(gender, language) %>%
summarise(meanscore = mean(score))
ggplot(df, aes(reorder_within(language, meanscore, gender), meanscore, fill = gender))
geom_bar(stat = "identity")
coord_flip()
scale_x_reordered()
facet_wrap(gender ~., scales = "free")