如何从零开始创建一个不在ggplot2 aes中的传奇?

时间:2022-04-27 22:10:27

Continue my question here: Variable line size using ggplot2

继续我的问题:使用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?

在aes中有什么方法可以让一个传说不存在吗?

Thanks for any suggestions.

谢谢你的任何建议。

1 个解决方案

#1


4  

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

你可以把第二个情节的传说添加到第一个情节中。

如何从零开始创建一个不在ggplot2 aes中的传奇?

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)

#1


4  

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

你可以把第二个情节的传说添加到第一个情节中。

如何从零开始创建一个不在ggplot2 aes中的传奇?

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)