问题描述
我用下面的代码绘制一个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命令中指定颜色
和形状
美学,并手动指定颜色和形状的比例,传说将出现。
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添加一个图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!