Presets:
Sys.setenv(lang = "EN")
library("ggplot2")
I use Gapminder data without Oceania here:
dat <- read.delim("http://www.stat.ubc.ca/~jenny/notOcto/STAT545A/examples/gapminder/data/gapminderDataFiveYear.txt")
dat = droplevels(subset(dat, continent != "Oceania"))
str(dat)
## 'data.frame': 1680 obs. of 6 variables:
## $ country : Factor w/ 140 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ year : int 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
## $ pop : num 8425333 9240934 10267083 11537966 13079460 ...
## $ continent: Factor w/ 4 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...
## $ lifeExp : num 28.8 30.3 32 34 36.1 ...
## $ gdpPercap: num 779 821 853 836 740 ...
Let's draw a scatterplot first.
plot = ggplot(data = dat) + geom_point(aes(x = gdpPercap, y = lifeExp, color = continent))
plot
To move the legend inside the plot, we use theme in which we specify legend.position:
plot + theme(legend.position = c(0.9, 0.2))
The first element in legend.position represents X coordinate and the second one represents Y coordinate in the plot. The bottom-left corner is (0,0) and the top-right corner is (1,1).
To change the background of the legend, you can use legend.background option:
plot + theme(legend.position = c(0.9, 0.2), legend.background = element_rect(color = "black",
fill = "grey90", size = 1, linetype = "solid"))
To align the elements horizontally, try the following code, which specifies legend.direction: (also note the effect of legend.position = 'bottom')
plot + theme(legend.position = "bottom", legend.background = element_rect(color = "black",
fill = "grey90", size = 1, linetype = "solid"), legend.direction = "horizontal")
For more options, type ?ggplot2::theme in the R console.