5

Continue my question here: Variable line size using ggplot2

I can create a figure with these codes.

x <- 1:100
y <- x * x 
z <- abs(cos(x * pi / (max(x))))

df <- data.frame(x = x, y = y, z = z)
library(ggplot2)


mult <- 200
ggplot(df, aes(x, y)) + geom_line() + geom_ribbon(aes(ymin=y-mult*z, ymax=y+mult*z))

But my question now is how to create a legend to reflect the size of line. For example, legend in this figure

    ggplot(df, aes(x, y, size = z)) + geom_line()

Is there any way to and a legend from scratch which doesn't exist in the aes?

Thanks for any suggestions.

Community
  • 1
  • 1
Bangyou
  • 9,462
  • 16
  • 62
  • 94
  • 1
    Here's a good guide on adding additional legend outside `aes()`:http://stackoverflow.com/questions/16389636/in-ggplot2-how-can-i-add-additional-legend – tonytonov Jan 22 '14 at 09:46
  • Thanks for your comments. It is very helpful for me. I just created a invisible layer to create a legend. – Bangyou Jan 22 '14 at 09:57

1 Answers1

5

You can add the legend of the second plot to the first one.

enter image description here

p1 <- ggplot(df, aes(x, y)) + geom_line() + geom_ribbon(aes(ymin=y-mult*z, ymax=y+mult*z))

p2 <- ggplot(df, aes(x, y, size = z)) + geom_line()

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)
}
legend <- g_legend(p2)
library(gridExtra)
pp <- arrangeGrob(p1 ,legend,
                  widths=c(5/4, 1/4),
                   ncol = 2)
agstudy
  • 119,832
  • 17
  • 199
  • 261