2017-04-12 161 views
1

有沒有一種方法來顯示圖例只在劇情?我試圖解決here,但沒有奏效:ggplot2只在一個陰謀的圖例

library(gridExtra) 
library(grid) 
g_legend<-function(a.gplot){ 
    tmp <- ggplot_gtable(ggplot_build(a.gplot)) 
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
    legend <- tmp$grobs[[leg]] 
    return(legend)} 

coverage_plot <- ggplot(data=m, aes(x=Time, y=Coverage, group=Technique, color=Technique)) + 
    geom_line(size=1) + 
    scale_colour_discrete(name="Technique") + 
    geom_point(aes(shape=Technique, colour = Technique), show.legend = T, size=3) + 
    scale_x_discrete(labels = seq(1, 30.0, by=1)) + 
    theme(legend.position="right", axis.text.x = element_text(angle = 90),text = element_text(size=14),legend.title=element_blank())+ 
    labs(x = "Time (minutes)")+ 
    scale_shape_discrete() + 
    guides(shape=guide_legend(override.aes=list(size=3, linetype=0))) 

mylegend<-g_legend(coverage_plot) 
p3 <- grid.draw(mylegend) 

p3這裏返回null!

任何建議請

回答

1

我希望我能評論... 不管怎樣,我想你的代碼與diamonds數據集的形式ggplot2有它工作正常。你認爲你可以分享你的數據?

library(ggplot2) 
library(gridExtra) 
library(grid) 
g_legend<-function(a.gplot){ 
    tmp <- ggplot_gtable(ggplot_build(a.gplot)) 
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
    legend <- tmp$grobs[[leg]] 
    return(legend)} 

coverage_plot <- ggplot(data=diamonds, aes(x=carat, y=price, group=clarity, color=clarity)) + 
    geom_line(size=1) + 
    scale_colour_discrete(name="clarity") + 
    geom_point(aes(colour = clarity), show.legend = T, size=3) + 
    scale_x_discrete(labels = seq(1, 30.0, by=1)) + 
    theme(legend.position="right", axis.text.x = element_text(angle = 90),text = element_text(size=14),legend.title=element_blank())+ 
    labs(x = "Time (minutes)")+ 
    scale_shape_discrete() + 
    guides(shape=guide_legend(override.aes=list(size=3, linetype=0))) 

mylegend<-g_legend(coverage_plot) 
p3 <- grid.draw(mylegend) 

我刪除從geom_pointshape因爲其中僅6形狀的符號和diamonds有8個變量。但除此之外它是一樣的。