Объединить базовую графику и графику ggplot в подрисовках графического устройства - PullRequest
1 голос
/ 18 апреля 2019

Я хочу создать массив графиков, используя основание R, каждый из которых имеет свой собственный график вставки, основанный на ggplot, выровненный по правому краю, немного ниже, чем верхний правый, чтобы я мог добавить текст выше.Примерно так (я нарисовал вставки ggplot с помощью MS Paint).

enter image description here

Я думаю, что это возможно при использовании viewports - аналогично этот вопрос.

# 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 Ответ

1 голос
/ 19 апреля 2019

Одним из решений (которое не подразумевает компрометацию на графиках, которые вы хотите создать) является использование аргумента layout в viewpoint() для настройки сетки для вспомогательных участков, которая перекрывает par(mfrow) / * 1004. * сетка.

Установка сетки точек обзора кратной par(mfrow) размерам позволяет вам удобно размещать ваши вспомогательные участки в нужной позиции сетки. Масштаб сетки точек обзора будет определять размер вспомогательного участка, поэтому большая сетка приведет к меньшим вспомогательным участкам.

# base R plots
par(mfrow = c(2, 3))
plot(x = mtcars$mpg, y = mtcars$cyl)
plot(x = mtcars$mpg, y = mtcars$disp)
plot(x = mtcars$mpg, y = mtcars$hp)
plot(x = mtcars$mpg, y = mtcars$drat)
plot(x = mtcars$mpg, y = mtcars$wt)
plot(x = mtcars$mpg, y = mtcars$qsec)

# set up viewpoint grid
library(grid)
pushViewport(viewport(layout=grid.layout(20, 30)))

# add ggplot subplots (code for these objects in question) at `layout.pos.row`, `layout.pos.col` 
print(g1, vp = viewport(height = unit(0.2, "npc"), width = unit(0.05, "npc"), 
                        layout.pos.row = 2, layout.pos.col = 9))
print(g2, vp = viewport(height = unit(0.2, "npc"), width = unit(0.05, "npc"), 
                        layout.pos.row = 2, layout.pos.col = 19))
print(g3, vp = viewport(height = unit(0.2, "npc"), width = unit(0.05, "npc"), 
                        layout.pos.row = 2, layout.pos.col = 29))
print(g4, vp = viewport(height = unit(0.2, "npc"), width = unit(0.05, "npc"), 
                        layout.pos.row = 12, layout.pos.col = 9))
print(g5, vp = viewport(height = unit(0.2, "npc"), width = unit(0.05, "npc"), 
                        layout.pos.row = 12, layout.pos.col = 19))
print(g6, vp = viewport(height = unit(0.2, "npc"), width = unit(0.05, "npc"), 
                        layout.pos.row = 12, layout.pos.col = 29))

enter image description here

Если у вас есть простые базовые R-графики, то другой способ - использовать ggplotify , чтобы преобразовать базовый график в ggplot, а затем использовать cowplot или patchwork для размещения. Я не мог заставить это работать для моих желаемых графиков, которые используют более сложный набор функций построения графиков (в базе R), чем те, что в фиктивном примере выше.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...