两个 geom_points 添加一个图例 [英] Two geom_points add a legend
问题描述
我使用以下代码绘制了一个 2 geom_point 图:
I plot a 2 geom_point graph with the 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')
我只想知道如何在右侧添加图例.具有相同的形状和颜色.三角形粉红色应该有传说女人",蓝色圆圈应该有传说男人".看起来很简单,但经过多次试验我无法做到.(我是 ggplot 的初学者).
I simply want to know how to add a legend on the right side. With the same shape and color. Triangle pink should have the legend "woman" and blue circle the legend "men". Seems quite simple but after many trial I could not do it. (I'm a beginner with ggplot).
推荐答案
如果您重命名原始数据框的列,然后使用reshape2::melt
将其融合为长格式,那就容易多了在ggplot2中处理.通过在 ggplot 命令中指定 color
和 shape
美学,并手动指定颜色和形状的比例,图例将出现.
If you rename your columns of the original data frame and then melt it into long format withreshape2::melt
, it's much easier to handle in ggplot2. By specifying the color
and shape
aesthetics in the ggplot command, and specifying the scales for the colors and shapes manually, the legend will 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))
这篇关于两个 geom_points 添加一个图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!