Seb_ISU
Seb_ISU

Reputation: 347

Selecting entries in legend of ggplot in R

I'm creating a figure using ggplot. That figure has 27 lines that I want to show but not emphasize, and two lines, mean and weighted mean, that I want to emphasize. I would like only these last two lines to appear into the legend of the plot. Here is my code:

p_plot <- ggplot(data = dta, aes(x = date, y = premium, colour = State)) + 
          geom_line(, show_guide=FALSE)  + 
          scale_color_manual(values=c(rep("gray60", 27))) 

p_plot <- p_plot + geom_line(aes(y = premium.m), colour = "blue", size = 1.25, 
          show_guide=TRUE) + geom_line(aes(y = premium.m.w), colour = "red", 
          size = 1.25, show_guide=c(TRUE)) + ylab("Pe/pg") 

p_plot

The show_guide = FALSE statement in the first geom_line seems to be overridden by the other show_guide=TRUE statements. How can I limit the number of entries in the legend of my figures to the lines "premium.m" and "premium.m.w"? Thank you.

Upvotes: 0

Views: 881

Answers (1)

Michele
Michele

Reputation: 8753

I think this should answer your question: (the code's been slightly modified but the concept is the same)

dta <- data.frame(date    = rep(seq.Date(as.Date("2010-01-01"), as.Date("2010-12-01"), "months"), 26),
                  premium = rnorm(12*26),
                  State   = rep(letters, each = 12))

library(ggplot2)


p_plot <- ggplot(data = dta) + 
  geom_line(aes(x = date, y = premium, group = State), colour = "grey60")

p_plot + geom_line(aes(x = unique(date), y = as.numeric(tapply(premium, date, mean)), colour = "mean"),
                   size = 1.25) +
  geom_line(aes(x = unique(date), y = as.numeric(tapply(premium, date, median)), colour = "median"),
            size = 1.25) + ylab("Pe/pg") +  scale_color_discrete("stats")

p_plot

enter image description here

However, this is just a (ugly) workaround and far from the best practice for data visualisation (especially for the purposes ggplot has been implemented for). Anyway, I could provide you with a more elegant solution if you edited your question adding more details.

Upvotes: 1

Related Questions