Various Manipulation around the legend in ggplot2

I now make it a rule when I need to search for the same tricks more than two times I turn it into a post. This one concern some manipulation of the legend in ggplot especially the legend title. The official website of ggplot2 is still the best place to start looking for answers: http://had.co.nz/ggplot2/

# a script to set up the legend name in ggplot
library(ggplot2)
data(mtcars)
# a scatterplot of miles per gallon against the displacement with a color
# scheme based on the numbers of gears
ggplot(mtcars, aes(x = disp, y = mpg, color = factor(gear))) + geom_point()

plot of chunk unnamed-chunk-2

# now to control the title of the legend (factor(gear) is not very nice) we
# can use the labs command
ggplot(mtcars, aes(x = disp, y = mpg, color = factor(gear))) + geom_point() + 
    labs(color = "Number of gears")

plot of chunk unnamed-chunk-3

# we can also change the legend labels from within the factor call
ggplot(mtcars, aes(x = disp, y = mpg, color = factor(gear, labels = c("Three", 
    "Four", "Five")))) + geom_point() + labs(color = "Number of gear")

plot of chunk unnamed-chunk-4

# this also work for other aesthetic
ggplot(mtcars, aes(x = disp, y = mpg, shape = factor(gear))) + geom_point() + 
    labs(shape = "Number of gear")

plot of chunk unnamed-chunk-5

# we can even combine two variation
ggplot(mtcars, aes(x = disp, y = mpg, shape = factor(gear), size = factor(gear))) + 
    geom_point() + labs(shape = "gear", size = "gear")

plot of chunk unnamed-chunk-6

# or remove the legend
ggplot(mtcars, aes(x = disp, y = mpg, shape = factor(gear))) + geom_point(show_guide = FALSE)

plot of chunk unnamed-chunk-7