watchtower watchtower - 3 months ago 8
R Question

Using colors in aes() function in ggplot2

I am new to

ggplot2
. I am trying to understand how to use
ggplot
. I am reading Wickham's book and still trying to wrap my head around how to use
aes()
function. In a related thread, we discussed that we should try to avoid using variables inside
aes()
i.e. "Don't put constants inside
aes()
- only put mappings to actual data columns."

My objective is to observe the behavior of ggplots when we have color inside
aes()
for labeling (as described in Wickham's book) and also override the color to print the color.

I started with this:

library(ggplot2)
data(mpg)
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(aes(colour = "loess"), method = "loess", se = FALSE) +
geom_smooth(aes(colour = "lm"), method = "lm", se = FALSE) +
labs(colour = "Method")


This nicely plots graphs and labels them. However, I am unhappy with the colors used. So, I experimented with using overriding colors again:

windows()
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
geom_smooth(aes(colour = "loess"), method = "loess", se = FALSE, color = "magenta") +
geom_smooth(aes(colour = "lm"), method = "lm", se = FALSE, color = "red") +
labs(colour ="Method")


I added color = "red" and we can see that
labs()
or
aes(color())
doesn't have any effect. Why does this happen? I'm curious. I'd appreciate thoughts.

Answer

When you specify, the colour outside aes() gg_plot does not consider the color information being part of the data (and it overwrites previous information) , so there is no legend to display anymore.

If you want to specify your own colors and keep the colour information as "relevant data" and not "display information", you should add a scale_colour_manual() command to specify the legend colours and leave the colour attribute in aes:

ggplot(mpg, aes(displ, hwy)) +
    geom_point() +
    geom_smooth(aes(colour = "loess"), method = "loess", se = FALSE) +
    geom_smooth(aes(colour = "lm"), method = "lm", se = FALSE) +  
    labs(colour ="Method") + scale_colour_manual(values = c("loess" = "magenta", "lm" = "red"))

enter image description here

Comments