刻面时,annotation_custom
在所有面板中绘制注释。因此,annotation-custom
可能不是最好的方法。这是使用包中的函数的两次尝试grid
。两者都不是完全自动的,但您可能能够调整其中一个以满足您的需求。他们设置了一个 2 X 2 网格,使用grid.show.layout()
命令显示。在第一个中,多面图填充了整个面板,右上角的视口包含徽标。碰巧的是,在您的情节中,徽标有明显的空间。请注意布局中视口占用的行和列的方式layout.pos.row
和方式。layout.pos.col
library(ggplot2)
library(png)
library(grid)
# Get the logo
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
g <- rasterGrob(img)
# Set the size of the viewport to contain the logo
size = unit(2, "cm")
# Get the graph
d <- ggplot(diamonds, aes(carat, price)) +
xlim(0, 2) +
stat_binhex(na.rm = TRUE) +
labs(title = 'Title') +
theme(aspect.ratio = 1) +
facet_wrap(~ color, scales = "free_x")
# Set up the layout for grid
heights = unit.c(size, unit(1, "npc") - size)
widths = unit.c(unit(1, "npc") - size, size)
lo = grid.layout(2, 2, widths = widths, heights = heights)
# Show the layout
grid.show.layout(lo)
# Position the elements within the viewports
grid.newpage()
pushViewport(viewport(layout = lo))
# The plot
pushViewport(viewport(layout.pos.row=1:2, layout.pos.col = 1:2))
print(d, newpage=FALSE)
popViewport()
# The logo
pushViewport(viewport(layout.pos.row=1, layout.pos.col = 2))
print(grid.draw(g), newpage=FALSE)
popViewport()
popViewport()
# To save the object
g = grid.grab()
grid.newpage()
grid.draw(g)
标题与徽标并不完全一致。一种解决方法是从 ggplot 中删除标题,绘制一个包含标题的单独 textGrob,然后将 textGrob 放置在包含徽标的视口旁边的左上角视口中。
# Get the logo
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
g <- rasterGrob(img)
# Set the size of the viewport to contain the logo
size = unit(2, "cm")
# Get the graph
d <- ggplot(diamonds, aes(carat, price)) +
xlim(0, 2) +
stat_binhex(na.rm = TRUE) +
# labs(title = 'Title') +
theme(aspect.ratio = 1) +
facet_wrap(~ color, scales = "free_x")
# and the title
title = textGrob("Title", gp = gpar(face = "bold", cex = 2))
# Set up the layout for grid
heights = unit.c(size, unit(1, "npc") - size)
widths = unit.c(unit(1, "npc") - 1.5*size, size)
lo = grid.layout(2, 2, widths = widths, heights = heights)
# Show the layout
grid.show.layout(lo)
# Position the elements within the viewports
grid.newpage()
pushViewport(viewport(layout = lo))
# The plot
pushViewport(viewport(layout.pos.row=2, layout.pos.col = 1:2))
print(d, newpage=FALSE)
popViewport()
# The logo
pushViewport(viewport(layout.pos.row=1, layout.pos.col = 2))
print(grid.draw(g), newpage=FALSE)
popViewport()
# The title
pushViewport(viewport(layout.pos.row=1, layout.pos.col = 1))
print(grid.draw(title), newpage=FALSE)
popViewport()
popViewport()
# To save the object
g = grid.grab()
grid.newpage()
grid.draw(g)