如何缩放子图的全部内容?

How to scale the entire contents of a subplot?

我找不到缩放整个子图(文本、线条等)的方法。我尝试过的所有内容(annotation_custom 与 coord_cartesian、ggdraw 和 draw_plot)都会缩放边界框而不是内容。

我想避免渲染情节然后使用图像。任何帮助表示赞赏。

示例代码:

mydata <- data.frame(x = c(1 ,2, 3), y= c('a', 'b', 'c'))
g <- ggplot(data = mydata) + geom_point(aes(x,y)) 
ggdraw(g + draw_plot(g, x=1, y= 1,width=1,height=1,scale=0.2))

结果:

A plot embedded in itself as subplot, with only the bounding box scaling

我不太确定你在问什么。如果这是关于如何在 中包含和缩放 (gg)plot a (gg)plot,这里是一个最小的可重现示例

gg1 <- ggplot(mtcars, aes(mpg, wt)) +
    geom_point() +
    geom_smooth(method = "lm")
gg2 <- ggplot(mtcars, aes(mpg, hp)) +
    geom_point()

gg1 + annotation_custom(
    ggplotGrob(gg2),
    xmin = 25, xmax = 34, ymin = 3.5, ymax = 5.5)

子图的维度由坐标(xmin, ymin)(xmax, ymax)决定。


更新

针对您的评论,也许这就是您想要的?

library(grid)
library(png)
fn <- tempfile("plot", fileext = "png")
ggsave(filename = fn, plot = gg2, device = "png")
img <- readPNG(fn)
gg1 + annotation_custom(
    rasterGrob(img, interpolate = T),
    xmin = 25, xmax = 28, ymin = 3.5, ymax = 5)

想法是将子图保存在临时 PNG 文件中;然后我们可以使用 png::readPNGwithgrid::rasterGrob` 将 PNG 显示为主图中的自定义注释。