2017-09-25 128 views
0

我在绘制自定义图例标签时遇到了麻烦,因为我之前也指定了自定义线型和颜色。在处理linetypes and line colors的自定义图例时,在stackoverflow上有类似的问题。但是,一旦您希望在上述两个属性的顶部指定图例标签,ggplot2看起来开始崩溃。控制ggplot图例中的线型,颜色和标签

这里是我的最低限度的可重复的例子:

library(ggplot2) 

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2), 
      treatment = c(rep("one", 2), rep("two", "2"))) 

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) + 
    geom_line() + 
    scale_linetype_manual(values = c(1, 3), 
         labels = c("Treatment one", "Treatment two")) + 
    scale_color_manual(values = c("black", "red")) 

上面的代码的结果在下面的图表

Setting labels in either scale_linetype_manual or scale_color_manual results in two legends being created.

设置在任一正在创建scale_linetype_manual()scale_color_manual()导致两个不同的传说标签。具有正确的线条的人将永远是无色的。另一方面,具有正确颜色的人不能正确表示线型(只有实线)。

有没有办法在ggplot2中同时控制颜色,线条类型和图例标签?或者,这是一个包的限制,我应该从getgo的数据框中正确指定标签?

回答

2

scale_linetype_manual()scale_color_manual()制作标签。

library(ggplot2) 

df <- data.frame(x = rep(1:2, 2), y = c(1, 3, 2, 2), 
       treatment = c(rep("one", 2), rep("two", "2"))) 

ggplot(df, aes(x = x, y = y, colour = treatment, linetype = treatment)) + 
    geom_line() + 
    scale_linetype_manual(values = c(1, 3), 
         labels = c("Treatment one", "Treatment two")) + 
    scale_color_manual(values = c("black", "red"), 
        labels = c("Treatment one", "Treatment two")) 

enter image description here