Based on the data and code below, I am unable to define colors
for males
and females
under column Type
.
I did find this question, but is there a way to do this without having to add a color
column
?
I did try adding the following to the code but it returns an error:
scale_fill_manual(values=c("#FC921F",
"#149ECE", Type))
Error in is_missing(values) : object 'Type' not found
ggplot scale_fill_manual within groups
Desired colors:
Male: #149ECE
Female: #FC921F
Data (pop_gen_df
):
structure(list(age_group = c("< 5 years", "5 - 14", "15 - 24",
"25 - 34", "35 - 44", "45 - 54", "55 - 64", "65 - 74",
"75 - 84", "85 +", "< 5 years", "5 - 14", "15 - 24", "25 - 34",
"35 - 44", "45 - 54", "55 - 64", "65 - 74", "75 - 84",
"85 +"), Type = c("males", "males", "males", "males", "males",
"males", "males", "males", "males", "males", "females", "females",
"females", "females", "females", "females", "females", "females",
"females", "females"), Value = c(-6, -13, -13, -15, -17, -15,
-11, -6, -3, -1, 6, 12, 12, 14, 16, 15, 12, 7, 4, 2)), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"))
Code:
library(tidyverse)
library(plotly)
# Plot
gg_pop_hisp = ggplot(pop_hisp_df, aes(x = age_group, y = Value, fill = Type)) +
geom_bar(data = subset(pop_hisp_df, Type == "females"), stat = "identity") +
geom_bar(data = subset(pop_hisp_df, Type == "males"), stat = "identity") +
scale_y_continuous(labels = function(z) paste0(abs(z), "%")) + # CHANGE
scale_fill_discrete(name = "Legend", labels = c("Females", "Males")) +
ggtitle("HISPANIC POPULATION BY GENDER AND AGE GROUP") +
labs(x = "PERCENTAGE POPULATION", y = "AGE GROUPS", fill = "Gender") +
theme_classic() +
coord_flip()
# Interactive
ggplotly(gg_pop_hisp)