I want to use ggplot
to create a graph that plots individual data points in one color and the mean in another color, then have a legend that explains the colors. Here are three attempts that don't quite work:
library(ggplot2)
library(dplyr)
# Create new tbl_df with average hp for each transmission
avghp <- mtcars %>% group_by(am) %>% summarize(hp=mean(hp))
# Correct dots and colors, no legend
g1 <- ggplot(mtcars, aes(x=am, y=hp)) +
geom_point(colour="blue" )+
geom_point(data=avghp, colour="red", size=4)
# Legend, but colors changed
g2 <- ggplot(mtcars, aes(x=am, y=hp)) +
geom_point(aes( colour="Individual"))+
geom_point(data=avghp, aes(colour="Average"), size=4)
# Correct colors in graph, but not in legend
g3 <- ggplot(mtcars, aes(x=am, y=hp)) +
geom_point(aes(fill="Individual"), colour="blue")+
geom_point(data=avghp, aes(fill="Average"), colour="red", size=4)
g1
shows the individual data points in blue, and the averages in red, but there's no legend because the colors aren't in an aes()
. g2
creates the legend, but doesn't use the same colors as in g1
. g3
moves the definitions of the colors outside the aes()
and used fill()
to create the legend, but then the dots on the legend are both blue.
How can I create something like g3
but where the legend shows a red dot for the average hp, and a blue for the individuals? Or, how can I specify specific colors in g2
?