有没有办法让grid.arrange()充当split.screen()?我想在图例的正下方安排一张桌子。
#create histogram
my_hist<-ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
#create inset table
my_table<- tableGrob(head(diamonds)[,1:3],gpar.coretext =gpar(fontsize=8),gpar.coltext=gpar(fontsize=8), gpar.rowtext=gpar(fontsize=8))
grid.arrange(my_hist,my_table, ncol=2)
产生:
但我希望它看起来大致像这样:
我尝试过 split.screen () 但它似乎不适用于 ggplot 类型的图形。有什么建议吗?谢谢。
Dickoa 的回答非常简洁。我的可以让你更好地控制元素。
my_hist <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
#create inset table
my_table <- tableGrob(head(diamonds)[,1:3], gpar.coretext = gpar(fontsize=8), gpar.coltext=gpar(fontsize=8), gpar.rowtext=gpar(fontsize=8))
#Extract Legend
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(my_hist)
#Create the viewports, push them, draw and go up
grid.newpage()
vp1 <- viewport(width = 0.75, height = 1, x = 0.375, y = .5)
vpleg <- viewport(width = 0.25, height = 0.5, x = 0.85, y = 0.75)
subvp <- viewport(width = 0.3, height = 0.3, x = 0.85, y = 0.25)
print(my_hist + opts(legend.position = "none"), vp = vp1)
upViewport(0)
pushViewport(vpleg)
grid.draw(legend)
#Make the new viewport active and draw
upViewport(0)
pushViewport(subvp)
grid.draw(my_table)
首先你应该看一下这个Wiki,有很多例子(看看arrangeGrob)。 所以使用这些例子,我设法得到了这个解决方案
require(gridExtra)
require(ggplot2)
## original graph
my_hist <- ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar()
## get the legend
tmp <- ggplot_gtable(ggplot_build(my_hist))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
## create inset table
my_table <- tableGrob(head(diamonds)[,1:3],gpar.coretext =gpar(fontsize=8),gpar.coltext=gpar(fontsize=8), gpar.rowtext=gpar(fontsize=8))
### final result
grid.arrange(my_hist + opts(legend.position = "none"), arrangeGrob(legend, my_table), ncol = 2)
使用
flextable
和 cowplot
添加方法:
library(flextable)
library(tidyverse)
library(cowplot)
my_hist <- ggplot(diamonds, aes(clarity, fill = cut)) +
geom_bar()
#create inset table
table <- head(diamonds)[,1:3] %>%
flextable() %>%
flextable::as_raster()
ggdraw(my_hist) +
draw_plot(grid::rasterGrob(table), x = 0.8, y = 0.09, hjust = 0, vjust = 0, halign = 1, valign = 1,
width = .2,
height = .2)