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()
# 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")
# 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")
# this also work for other aesthetic
ggplot(mtcars, aes(x = disp, y = mpg, shape = factor(gear))) + geom_point() +
labs(shape = "Number of gear")
# 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")
# or remove the legend
ggplot(mtcars, aes(x = disp, y = mpg, shape = factor(gear))) + geom_point(show_guide = FALSE)