R的ggplot中的自定义图例

时间:2017-05-01 17:50:17

标签: r ggplot2 legend

数据框:

df <- data.frame('X' = c('a','a','b','b','c','c','d','d'), 'legend' = c('a','b','a','b','c','d','c','d'), 'Y' = c(100,50,50,100,150,100,150,100))

图表:

ggplot(data=df, aes(x=X, y=Y, group=legend, colour=legend)) + 
geom_line(size = 1) + 
geom_point(size = 3) +
scale_color_manual(values=c("blue", "red","blue", "red"), labels = c('blue','red')) + 
scale_x_discrete(labels = c('Group 1','Group 1','Group 2','Group 2'))

输出:

http://imgur.com/a/U62PU

当我这样做时,图例中会显示“蓝色”,“红色”,“NA”,“NA”。如何从图例中删除NA,因此它只显示“蓝色,红色”?

1 个答案:

答案 0 :(得分:3)

您始终可以在breaks内设置scale_color_manual。这样的事情应该有效:

  ggplot(data=df, aes(x=X, y=Y, group=legend, colour=legend)) + 
    geom_line(size = 1) + 
    geom_point(size = 3) +
    scale_color_manual(values=c("blue", "red","blue", "red"), 
                     labels = c('blue','red'), breaks = c("a", "b")) + #Set the breaks here
    scale_x_discrete(labels = c('Group 1','Group 1','Group 2','Group 2'))

我们只保留前两个组,因为我们想要重新标记在图例redblue中只有2个值 enter image description here