I am creating a population pyramid style bar chart in R of the number of work internships by age category, by gender. In a previous step I have summarized the data grouping by age and gender to get counts of internships. I then multiplied the Male counts by -1 for proper graph formatting.
All is well and good until I go to manually change the colors of the geom_bars
. When I set them manually or use the scale_fill_manual
option my chart rotates. Also can't quite figure out how to change the fonts.
This code works
#WEs
pyramidWE2 <- ggplot(WE2, aes(x = Age, y =n, fill = Gender)) +
geom_bar(data = subset(WE2, Gender == "F"), stat = "identity") +
geom_bar(data = subset(WE2, Gender == "M"), stat = "identity") +
scale_y_continuous(breaks=seq(-100,100,10),labels=abs(seq(-100,100,10))) +
#commented out: scale_fill_manual(values =c("pink","light blue")) +
#commented out: labs(x = "Age(Years)", y = "Number of WE's", title = "Number of Work Experiences by Gender, Colorado, 2018", font.lab="Trebuchet MS")
coord_flip()
pyramidWE2
resulting graph:
But this code rotates the graph and removes the legend
#WEs
pyramidWE2 <- ggplot(WE2, aes(x = Age, y =n, fill = Gender)) +
geom_bar(data = subset(WE2, Gender == "F"), stat = "identity") +
geom_bar(data = subset(WE2, Gender == "M"), stat = "identity") +
scale_y_continuous(breaks=seq(-100,100,10),labels=abs(seq(-100,100,10))) +
scale_fill_manual(values =c("pink","light blue")) +
labs(x = "Age(Years)", y = "Number of WE's", title = "Number of Work Experiences by Gender, Colorado, 2018", font.lab="Trebuchet MS")
coord_flip()
pyramidWE2
resulting graph:
A '+'
is missing in one of your ggplot function. (after the labs()
).
library(tidyverse)
WE2 <- data.frame(
Age = rep(seq(20, 60, 5), 2),
Gender = rep(c('H', 'F'), each = 9),
n = rnorm(18, 40, 20) %>% ceiling()
) %>%
mutate(n = ifelse(Gender == 'F', -n, n))
WE2 %>% ggplot(aes(x = Age, y = n, fill = Gender)) +
geom_bar(data = subset(WE2, Gender == 'H'), stat = "identity") +
geom_bar(data = subset(WE2, Gender == 'F'), stat = "identity") +
scale_y_continuous(breaks = seq(-100,100,10), labels = abs(seq(-100,100,10))) +
scale_fill_manual(values = c("pink", "light blue")) +
labs(x = "Age(Years)", y = "Number of WE's", title = "Number of Work Experiences by Gender, Colorado, 2018", font.lab="Trebuchet MS") +
coord_flip()