我试图在grid.arrange或arrangeGrob派生的输出中添加徽标。
我有以下代码:
库(GGPLOT2)
p1 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet, group=Chick)) +
geom_line() +
ggtitle("Growth curve for individual chicks")
p2 <- ggplot(ChickWeight, aes(x=Time, y=weight, colour=Diet)) +
geom_point(alpha=.3) +
geom_smooth(alpha=.2, size=1) +
ggtitle("Fitted growth curve per diet")
p3 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, colour=Diet))
+ geom_density() +
ggtitle("Final weight, by diet")
p4 <- ggplot(subset(ChickWeight, Time==21), aes(x=weight, fill=Diet)) +
geom_histogram(colour="black", binwidth=50) +
ggtitle("Final weight, by diet")
我使用grid.arrange(p1,p2,p3,p4,ncol = 2,clip = 4)将多个绘图放到一个绘图中。
但是我在向上面的grid.arrange输出插入徽标时遇到了问题。
我尝试了以下方法,但收到了以下错误消息。
b <- rasterGrob(img, width=unit(5,"cm"), x = unit(40,"cm"))
z1 <- ggplotGrob(grid.arrange(p1,p2,p3,p4,ncol=2,clip=4))
z1<- gtable_add_grob(z1,b, t=1,l=1, r=5)
grid.newpage()
grid.draw(z1)
错误:图中没有图层
是否有一种方法或方法可以在arrangeGrob或grid.arrange之后向输出添加徽标。
答案 0 :(得分:2)
不是gtable
答案,但添加可能有用的徽标的方式略有不同
library(ggplot2)
library(grid)
library(png)
library(gridExtra)
# Read png
img <- readPNG(system.file("img", "Rlogo.png", package="png"), FALSE)
# Create grobs to add to plot
my_g <- grobTree(rectGrob(gp=gpar(fill="black")),
textGrob("Some text", x=0, hjust=0, gp=gpar(col="white")),
rasterGrob(img, x=1, hjust=1))
# Plot
p <- ggplot(mtcars , aes(wt , mpg)) +
geom_line() +
theme(plot.margin=unit(c(1, 1, 1,1), "cm"))
# Add as a strip along top
grid.arrange(my_g, arrangeGrob(p,p,p,p, ncol=2), heights=c(1, 9))