0

[Edited to have runnable code and with second approach]

I've found several links that seem relevant here, here and here but can't see my way straight to figuring out how to apply them to my challenge: I have a line plot created with ggplot2 that draws on a data frame including upper and lower confidence intervals. I want them to simply show in the legend as "99% CIs", not separately as, say, "Upper CI" and "Lower CI".

library(ggplot2)
library(reshape2)

gmm   <- data.frame(x=runif(10), observed=runif(10), theoretical=runif(10), 
                upper=runif(10), lower=runif(10))
gmm.m <- melt(gmm, id="x")

p1 <- ggplot(data=gmm.m, aes(x, value, colour=variable)) + geom_line() 

p1 <- p1 + scale_colour_manual(
        values=c("black", "#F8766D", "#7DAF01", "#7DAF01"), 
        labels=c("Observed","Theoretical","99% Confidence Intervals",""))

Setting the last legend label to the empty "" is as close as I've come to sorting this out. So just to be clear, I want both CIs to show in the same colour on the line plot, I just don't want them to show up as separate legend items.

I suspect that one way to do it is to melt the other variables while skipping 'lower', and to then add this afterwards. But, aside from (personally) finding that approach inelegant (easier to say "add everything but hide legend for this one"), my attempts to do that have also failed.

library(ggplot2)
library(reshape2)
gmm   <- data.frame(x=runif(10), observed=runif(10), theoretical=runif(10), upper=runif(10))
gmm.m <- melt(gmm, id="x")
gmm.b <- data.frame(x=runif(10),variable='lower', value=runif(10))
p1 <- ggplot(data=gmm.m, aes(x, value, colour=variable)) + geom_line() + scale_colour_manual(values=c("black", "#F8766D", "#7DAF01"), labels=c("Observed","Theoretical","99% Confidence Intervals",""))
p1 <- p1 + geom_line(data=gmm.b, aes(x=x, y=value, legend=FALSE))
plot(p1)
Community
  • 1
  • 1
  • 3
    You've made it very difficult to answer by not providing a reproducible example. But if I had to guess, I'd say that the answer would involve using both the color aesthetic to set the labels/legend the way you want and to use the group aesthetic to ensure each line is drawn properly. – joran Jun 06 '13 at 14:24
  • Hopefully the edits make this a bit easier to follow. Sorry about that, I was posting at the end of a long, hard day of coding. – user1600439 Jun 07 '13 at 06:52

1 Answers1

1

Here's the method I was referring to in my comment:

dat <- rbind(gmm.m,gmm.b)
dat$variable <- as.character(dat$variable)
dat$var1 <- dat$variable
dat$var1[dat$var1 %in% c('upper','lower')] <- '99% CI'

ggplot(dat,aes(x = x,y = value)) + 
    geom_line(aes(colour = var1,group = variable))

(I only convert to character because its a bit simpler to manipulate than factors, IMHO.)

As I said, use one variable to delineate the grouping (for drawing the lines) and another variable to delineate which points get the same color.

joran
  • 169,992
  • 32
  • 429
  • 468