Search code examples
rggplot2legend-properties

Change ggplot coloured lines in legend to squares or circles


Instead of the coloured lines on a grey background that currently make up the legend key, I would like squares or circles of colour next to the key label in order for the colors to be easily visible. How can I do that? Here is a code snippet to use as an example:

 mry <- do.call(rbind, by(movies, round(movies$rating), function(df) {
   nums <- tapply(df$length, df$year, length)
   data.frame(rating=round(df$rating[1]), year = as.numeric(names(nums)),
   number=as.vector(nums))
 }))

ggplot(mry, aes(x=year, y=number, colour=factor(rating))) + geom_line() +
scale_colour_brewer(palette="YlGnBu")

Solution

  • one hack coming up to make circles....

    ggplot(mry, aes(x=year, y=number, colour=factor(rating))) +
      scale_colour_brewer(palette="YlGnBu") +  
      geom_point()  +      
      geom_point(size=5,colour="white",show_guide=FALSE)  +
      opts(
        panel.background = theme_rect(fill =  "transparent"), 
        panel.grid.minor = theme_blank(),
        panel.grid.major = theme_blank(),
        plot.background = theme_rect(fill = "transparent",colour = NA)
      ) +  geom_line(show_guide=FALSE)
    

    enter image description here