当仅在一部分线上绘制点时,R中的ggplot2图例

时间:2018-03-13 19:40:44

标签: r ggplot2

我使用ggplot创建了一个线图,该ggplot有10行,并且使用子集将点(不同形状)添加到只有两行。但是,图例显示所有行上的点。有没有办法让图例只在有点的线上显示一个点(正确的形状)?这是我的代码:

aplot <- ggplot(weekly, aes(x=week, y=alpha, group=bin, color=bin))
 +geom_line()

aplot <- aplot +geom_point(aes(x=week, y=alpha, group=bin, 
color=bin), size=3, shape=16, subset(weekly, bin %in% c("b")))

aplot <- aplot +geom_point(aes(x=week, y=alpha, group=bin, color=bin), 
size=3, shape=17, subset(weekly, bin %in% c("t")))

其中data.frame每周看起来像:

bin  week  alpha
b    1     10
b    2     12
b    3     16
t    1     14
t    2     18
t    3     8
m    1     13
m    2     19
m    3     9
.    .     .
.    .     .
.    .     .

谢谢!

1 个答案:

答案 0 :(得分:0)

aplot <- ggplot() +
         geom_line(data = weekly, aes(x = week, y = alpha, group = bin, color = bin) +
         geom_point(data = subset(weekly, bin %in% c("t")), aes(x = week, y = alpha, group = bin, color = bin), size = 3, shape = 17) +
         geom_point(data = subset(weekly, bin %in% c("b")), aes(x = week, y = alpha, group = bin, color = bin), size = 3, shape = 16) + 
         guides(color = guide_legend(override.aes = list(shape = c(NA, 16, 17))))

编辑:感谢您提供数据样本并澄清您的问题。我使用guides参数测试了代码,现在它显示了不同的图例形状