r - Two geom_points add a legend -
i plot 2 geom_point graph following code:
source("http://www.openintro.org/stat/data/arbuthnot.r") library(ggplot2) ggplot() + geom_point(aes(x = year,y = boys),data=arbuthnot,colour = '#3399ff') + geom_point(aes(x = year,y = girls),data=arbuthnot,shape = 17,colour = '#ff00ff') + xlab(label = 'year') + ylab(label = 'rate')
i want know how add legend on right side. same shape , color. triangle pink should have legend "woman" , blue circle legend "men". seems quite simple after many trial not it. (i'm beginner ggplot).
if rename columns of original data frame , melt long format withreshape2::melt
, it's easier handle in ggplot2. specifying color
, shape
aesthetics in ggplot command, , specifying scales colors , shapes manually, legend appear.
source("http://www.openintro.org/stat/data/arbuthnot.r") library(ggplot2) library(reshape2) names(arbuthnot) <- c("year", "men", "women") arbuthnot.melt <- melt(arbuthnot, id.vars = 'year', variable.name = 'sex', value.name = 'rate') ggplot(arbuthnot.melt, aes(x = year, y = rate, shape = sex, color = sex))+ geom_point() + scale_color_manual(values = c("women" = '#ff00ff','men' = '#3399ff')) + scale_shape_manual(values = c('women' = 17, 'men' = 16))
Comments
Post a Comment