Base Plot
xy <- data.frame(x=1:10, y=10:1, type = rep(LETTERS[1:2], each=5))
p=ggplot(data=xy)+geom_point(aes(x=x,y=y,color=type))
p
legend.background (rect)
# color does not work, use colour instead
p+opts(legend.background=theme_rect(colour="purple",fill="pink",size=3,linetype="dashed"))
legend.key (rect)
p+opts(legend.key=theme_rect(colour='purple',fill='pink',size=0.5,linetype='dashed'))
legend.key.size (unit)
# to use unit, you need to load package grid, i.e. library(grid)
p+opts(legend.key.size=unit(2,'cm'))
legend.key.width (unit)
p+opts(legend.key.width=unit(5,'cm'))
legend.text (text)
p+opts(legend.text = theme_text(colour = 'red', angle = 45, size = 10, hjust = 3, vjust = 3, face = 'bold'))
change legend labels
# breaks=c('A','B'), 'A' and 'B' are the default legend in xy
p+scale_colour_hue(name="my legend", breaks=c('A','B'), labels=c('AAA','BBB'))
legend.title (text)
p+opts(legend.title = theme_text(colour = 'red', angle = 45, size = 10, hjust = 3, vjust = 7, face = 'italic'))
legend.position (?)
# get rid of legend
p+opts(legend.position='none')
# move legend to the left
p+opts(legend.position='left')
# define relative coordinates on plot c(x, y) between 0 and 1
p+opts(legend.position=c(0.5,0.5))
legend.justification (?)
# Justification defines which side of the legend that the legend.position coordinates refer to
p+ opts(legend.justification = 'right', legend.position=c(0.25,0.3))
# can use left, right, centre or numeric value (0 ≤ x ≤ 1)
Reference
1. https://github.com/hadley/ggplot2/wiki/Legend-Attributes