2

Is there a way to show the legend only in the plot? I tried the solution here but didn't work:

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)

The p3 here return null!

Any suggestions please

Community
  • 1
  • 1
Nasser
  • 2,118
  • 6
  • 33
  • 56

1 Answers1

2

I wish I could comment.. Anyway, I tried your code with the diamonds dataset form ggplot2 and there it works fine. You think you can share your data?

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)

I removed the shape from geom_point since there where only 6 shape symbols and diamonds has 8 variables. But other than that it's the same.

Erik Schutte
  • 300
  • 1
  • 12