How to explicitly map labels and colors to variable values in ggplot

How can I explicitly (rather than positionally) control labels and color mappings in ggplot?

I can control labels and fill colors with positional arguments like so

mtcars %>% 
	count(cyl) %>% 
	mutate(cyl = as.factor(cyl)) %>% 
	ggplot(aes(x = cyl, y = n, fill = cyl)) + 
	geom_col() + 
	scale_x_discrete(labels = c('four', 'six', 'eight')) + 
	scale_fill_manual(values = c('red', 'blue', 'green'))

But I want more explicit mappings like this for scenarios where there is a risk of mislabeling/miscoloring. I think this can be done within ggplot.

mtcars %>% 
	count(cyl) %>% 
	mutate(cyl = as.factor(cyl)) %>% 
	ggplot(aes(x = cyl, y = n, fill = cyl)) + 
	geom_col() + 
	scale_x_discrete(labels = c(4 = 'four', 6 = 'six', 8 = 'eight')) + 
	scale_fill_manual(values = c(4 = 'red', 6 = 'blue', 8 = 'green'))

Hi @joepowers16

You were very close actually. You just needed some extra quotation marks:

mtcars %>% 
  count(cyl) %>% 
  mutate(cyl = as.factor(cyl)) %>% 
  ggplot(aes(x = cyl, y = n, fill = cyl)) + 
  geom_col() + 
  scale_x_discrete(labels = c('4' = 'four', '6' = 'six', '8' = 'eight')) + 
  scale_fill_manual(values = c('4' = 'red', '6' = 'blue', '8' = 'green'))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.