在图形设备的子图中组合基础图形和ggplot图形

时间:2019-04-18 03:53:33

标签: r ggplot2 plot viewport

我想使用基数R生成一系列图,每个图都有基于ggplot的自己的插入图,该图以右对齐,比右上角略低,以便在上面添加一些文本。像这样的东西(我已经用MS Paint绘制了ggplot插件)。

enter image description here

我认为使用viewports可以实现这一点-与this问题类似。

# ggplot code for inserts
library(tidyverse)
g1 <- ggplot(data = mtcars, mapping = aes(x = cyl)) +
  geom_density(colour = "red") +
  theme_void()
g2 <- ggplot(data = mtcars, mapping = aes(x = disp)) +
  geom_density(colour = "red") +
  theme_void()
g3 <- ggplot(data = mtcars, mapping = aes(x = hp)) +
  geom_density(colour = "red") +
  theme_void()
g4 <- ggplot(data = mtcars, mapping = aes(x = drat)) +
  geom_density(colour = "red") +
  theme_void()
g5 <- ggplot(data = mtcars, mapping = aes(x = wt)) +
  geom_density(colour = "red") +
  theme_void()
g6 <- ggplot(data = mtcars, mapping = aes(x = qsec)) +
  geom_density(colour = "red") +
  theme_void()

我尝试使用视口功能,但是无法将插入物相对于每个子图形放置(我认为它们均基于整个图形设备放置)...

library(grid)
par(mfrow = c(2, 3))
vps <- baseViewports()
plot(x = mtcars$mpg, y = mtcars$cyl)
pushViewport(vps$figure)
print(g1, vp = viewport(height = unit(0.2, "npc"), width = unit(0.2, "npc"), x = 1, y = 0.8, just  = 1))
plot(x = mtcars$mpg, y = mtcars$disp)
pushViewport(vps$figure)
# upViewport()
# popViewport()
print(g2, vp = viewport(height = unit(0.2, "npc"), width = unit(0.2, "npc"), x = 1, y = 0.8, just  = 1))
plot(x = mtcars$mpg, y = mtcars$hp)
print(g3, vp = viewport(height = unit(0.2, "npc"), width = unit(0.2, "npc"), x = 1, y = 0.8, just  = 1))
plot(x = mtcars$mpg, y = mtcars$drat)
print(g4, vp = viewport(height = unit(0.2, "npc"), width = unit(0.2, "npc"), x = 1, y = 0.8, just  = 1))
plot(x = mtcars$mpg, y = mtcars$wt)
print(g5, vp = viewport(height = unit(0.2, "npc"), width = unit(0.2, "npc"), x = 1, y = 0.8, just  = 1))
plot(x = mtcars$mpg, y = mtcars$qsec)
print(g6, vp = viewport(height = unit(0.2, "npc"), width = unit(0.2, "npc"), x = 1, y = 0.8, just  = 1))

enter image description here

1 个答案:

答案 0 :(得分:1)

一种解决方案(不涉及折衷于要绘制的图)是使用layout中的viewpoint()参数为子图设置网格,该网格覆盖{{ 1}} / par(mfrow)网格。

将视点网格设置为par(mfcol)维的倍数,可以将子图很好地放置在所需的网格位置。视点网格的比例将决定子图的大小-因此,较大的网格将导致较小的子图。

par(mfrow)

enter image description here

如果您有简单的基本R图,则另一种方法是使用ggplotify将基本图转换为ggplot,然后使用Cowplot或拼凑法进行放置。我无法在所需的绘图中使用此功能,该绘图使用的绘图函数集比在上面的虚拟示例中复杂得多(在基础R中)。