How to create a legend from scratch which is not in aes of ggplot2?

随声附和 提交于 2021-02-07 19:25:22

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/21279247/how-to-create-a-legend-from-scratch-which-is-not-in-aes-of-ggplot2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!