识别和删除ggplot对象中的图例

时间:2015-10-29 09:32:00

标签: r ggplot2

我正在使用来自survMisc包的autoplot,它会生成ggplot生存曲线。 然后我添加一个geom_line对象,这会导致生成一个重复的图例。 enter image description here

data(kidney, package="KMsurv")
s1 <- survfit(Surv(time, delta)~1 , data=kidney)
p1<-autoplot(s1, type="fill", survLineSize=2)
d1=data.frame(x=seq(0,20,10),y=seq(0,1,.5),lab=rep('lin'))
p1$plot+geom_line(data=d1,aes_string(x='x',y='y', colour='lab'),inherit.aes=F)

阅读r cookbook 它似乎建议我应该使用scale_XXX_discrete来替换xxx = color / fill / ...根据使用的内容。现在我如何找出autoplot使用的内容?有没有一种简单的方法来识别图例来源(以及使用的标签 - 例如它是1还是'1')?

我尝试添加

  + scale_colour_discrete(name='Estimate',
                      breaks=c(1,'lin'),
                      labels=c('observed','lin')) +
 scale_fill_discrete(name='Estimate',
                    breaks=c(1,'lin'),
                    labels=c('observed','lin')) +

它将1改为'观察'但我仍然有一个重复的传奇

p1$plot$scales
Reference class object of class "Scales"
Field "scales":
[[1]]
discrete_scale(aesthetics = "colour", scale_name = "brewer", 
    palette = brewer_pal(type, palette), guide = ..1)

[[2]]
discrete_scale(aesthetics = "fill", scale_name = "brewer", palette =    brewer_pal(type, 
palette), guide = ..1)

[[3]]
continuous_scale(aesthetics = c("y", "ymin", "ymax", "yend", 
"yintercept", "ymin_final", "ymax_final"), scale_name = "position_c", 
palette = identity, name = ..1, expand = expand, guide = "none")

[[4]]
continuous_scale(aesthetics = c("x", "xmin", "xmax", "xend", 
"xintercept"), scale_name = "position_c", palette = identity, 
name = ..1, breaks = ..2, expand = expand, guide = "none")

1 个答案:

答案 0 :(得分:1)

如果您查看survMisc:::autoplot.survfit的代码,您会看到设置了两个比例:scale_colour_brewerscale_fill_brewer。在您发布的代码中,只有colour比例受到其他geom_line图层的影响。要拥有单个图例,您也需要处理fill比例。

library(ggplot2)
library(survMisc)
library(KMsurv)

data(kidney, package="KMsurv")

s1 <- survfit(Surv(time, delta) ~ 1 , data = kidney)
p1 <- autoplot(s1, type = "fill", survLineSize = 2)
d1 <- data.frame(x = seq(0,20,10), y = seq(0,1,.5), lab = rep('lin'))

p1$plot + 
  geom_line(data = d1,
            aes_string(x = 'x',y = 'y', fill = 'lab',  colour = 'lab'),
            inherit.aes=F) 

enter image description here