假设我有一个 ggplot 对象:

library("ggplot2")
library("grid")
p <- qplot(0:10,0:10)

还有一些带框的网格页面:
grid.newpage()
vp <- viewport(width = unit(210, "mm"), height = unit(297, "mm"))
pushViewport(vp)

# Inner box:
box <- viewport(unit(105,"mm"),unit(150,"mm"),width=unit(150,"mm"),height=unit(150,"mm"))
pushViewport(box)
grid.rect()

我可以按如下方式拟合情节:
# Print ggplot plot:
upViewport()
print(p ,vp = box)

但我想在这个页面内完成绘图,以便绘图区域(不是边距)完全填充这个框,并且图例、轴标签等在绘图之外“溢出”。有没有办法做到这一点?

最佳答案

可能有比以下更简单的方法。

这使用 gtable 函数将 ggplot 分解为绘图面板和两个轴。然后将组件定位到视口(viewport)中,以便绘图面板完全填充内部框,但轴位于内部框的边界之外。红色边界线和旋转是为了证明(主要是对我自己)轴在外面但与内部框一起移动。

library(ggplot2)
library(gtable)
library(grid)

p <- qplot(0:10,0:10)

# Convert the plot to a grob
gt <- ggplotGrob(p)

# Extract panel, axes and axis labels
panel = gtable_filter(gt, "panel")
axis_l = gtable_filter(gt, "axis-l")
axis_b = gtable_filter(gt, "axis-b")
xlab = gtable_filter(gt, "xlab-b")
ylab = gtable_filter(gt, "ylab-l")

# Put labels and axes together
left = cbind(ylab, axis_l, size = "first")
bottom = rbind(axis_b, xlab, size = "last")

# Get their width / height
w = convertX(sum(left$width), "mm")
h = convertX(sum(bottom$height), "mm")

# Outer box
grid.newpage()
outerBox <- viewport(width = unit(125, "mm"), height = unit(150, "mm"))
pushViewport(outerBox)
grid.rect(gp = gpar(col = "red", fill = NA))

# Width and height of inner box (in mm)
width = 60
height = 70

# Inner box
innerBox <- viewport(x = unit(0.5, "npc"), y = unit(0.6, "npc"),
                width = unit(width, "mm"), height = unit(height, "mm"), angle = -30)

# Viewport for left axis and label
Vleft = viewport(x = unit(0, "npc") - .5*w, y = unit(0.5, "npc"),
                width = w, height = unit(height, "mm"))

# Viewport for bottom axis and label
Vbottom = viewport(x = unit(0.5, "npc"), y = unit(0, "npc") - .5*h,
                width = unit(width, "mm"), height = h)

pushViewport(innerBox)
grid.draw(panel)
grid.rect(gp = gpar(col = "red", fill = NA, lwd = 2))

pushViewport(Vbottom)
grid.draw(bottom)

upViewport()
pushViewport(Vleft)
grid.draw(left)

popViewport()
popViewport()
popViewport()

关于r - 使 ggplot 完全适合视口(viewport)大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29535760/

10-12 18:50