0

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)
Ed_Gravy
  • 1,841
  • 2
  • 11
  • 34
  • 3
    Use `scale_fill_manual(name = "Legend", values = c("females"="#FC921F", "males"="#149ECE"))` rather than `scale_fill_discrete()` – MrFlick Aug 12 '22 at 15:02
  • Thank you, but I also want to change the `Legend` names to `Females` and `Males`. But, I guess it would be better to change the names in the data itself. – Ed_Gravy Aug 12 '22 at 15:16
  • 2
    Then leave in the labels: `scale_fill_manual(name = "Legend", values = c("females"="#FC921F", "males"="#149ECE"), labels = c("Females", "Males"))` – MrFlick Aug 12 '22 at 15:17
  • @MrFlick, if you want kindly add this as an answer and I can accept it, thank you. – Ed_Gravy Aug 12 '22 at 15:20

0 Answers0