gpt4 book ai didi

r - 使 ggplot 完全适合视口(viewport)大小

转载 作者:行者123 更新时间:2023-12-01 12:36:15 25 4
gpt4 key购买 nike

假设我有一个 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()

enter image description here

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com