ggplot2 - правильно расположить нечетное количество графиков в одной фигуре - PullRequest
0 голосов
/ 23 октября 2018

У меня есть нечетное количество графиков, которые можно разместить на одной фигуре, и я хочу показать последний график с центром в последней строке рисунка.

Вот некоторые примеры данных:

library(ggplot2)
set.seed(99)

x_1 = data.frame(z = rnorm(100))
x_2 = data.frame(z = rnorm(100))
x_3 = data.frame(z = rnorm(100))

lst = list(x_1, x_2, x_3)

lst_p = list()

for (i in 1:length(lst)) {
    lst_p[[i]] = ggplot(data=lst[[i]], aes(lst[[i]]$z)) + 
    geom_histogram() +
        xlab("X LAB") +
        ylab("Y LAB") 
}

p_no_labels = lapply(lst_p, function(x) x + xlab("") + ylab(""))

title = cowplot::ggdraw() + cowplot::draw_label("test", size = 20)

p_grid = cowplot::plot_grid(plotlist = p_no_labels, ncol = 2)

print(cowplot::plot_grid(title, p_grid, 
                         ncol = 1, rel_heights = c(0.05, 1, 0.05)))

Я хочу третий сюжет в центре фигуры.Я использую cowplot.

Есть предложения?спасибо

enter image description here

Ответы [ 4 ]

0 голосов
/ 23 октября 2018

При этом используются grid и gridExtra для размещения графиков на матричном макете 2 × 4.Каждый из ваших сюжетов занимает два «слота».Два внешних «слота» в нижнем ряду изображены в виде пустых чисел для центрирования вашего графика.

# Convert to grobs
lst_p <- lapply(lst_p, ggplotGrob)

# Plot using gridExtra and grid
gridExtra::grid.arrange(lst_p[[1]], lst_p[[2]], grid::nullGrob(), lst_p[[3]], grid::nullGrob(),
                        layout_matrix = matrix(c(1,1,2,2,3,4,4,5), byrow = TRUE, ncol = 4))

enter image description here

0 голосов
/ 23 октября 2018

Необычайно элегантным решением было бы оставить средний участок пустым в первом ряду:

p_no_labels2<-list(p_no_labels[[1]],NULL,p_no_labels[[2]],NULL,p_no_labels[[3]])
p_grid = cowplot::plot_grid(plotlist = p_no_labels2, ncol = 3) 

enter image description here

0 голосов
/ 23 октября 2018

Использование вложенных cowplot::plot_grid с:

library(ggplot2)
set.seed(99)

x_1 = data.frame(z = rnorm(100))
x_2 = data.frame(z = rnorm(100))
x_3 = data.frame(z = rnorm(100))

lst = list(x_1, x_2, x_3)

lst_p = list()

for (i in 1:length(lst)) {
    lst_p[[i]] = ggplot(data=lst[[i]], aes(lst[[i]]$z)) + 
    geom_histogram() +
        xlab("X LAB") +
        ylab("Y LAB") 
}


p_no_labels = lapply(lst_p, function(x) x + xlab("") + ylab(""))

title = cowplot::ggdraw() + cowplot::draw_label("test", size = 20)
top_row = cowplot::plot_grid(p_no_labels[[1]], p_no_labels[[2]], ncol=2)
bottom_row = cowplot::plot_grid(NULL, p_no_labels[[2]], NULL, ncol=3, rel_widths=c(0.25,0.5,0.25))

cowplot::plot_grid(title, top_row, bottom_row, ncol=1, rel_heights=c(0.1,1,1))

0 голосов
/ 23 октября 2018

Вы можете использовать gridExtra::grid.arrange для этого.Все, что вам нужно сделать, это указать расположение графиков с помощью матрицы размещения.

library(ggplot2)
set.seed(99)

x_1 = data.frame(z = rnorm(100))
x_2 = data.frame(z = rnorm(100))
x_3 = data.frame(z = rnorm(100))

lst = list(x_1, x_2, x_3)

lst_p = list()

for (i in 1:length(lst)) {
lst_p[[i]] = ggplot(data=lst[[i]], aes(lst[[i]]$z)) + 
geom_histogram() +
xlab("X LAB") +
ylab("Y LAB") 
}

p_no_labels = lapply(lst_p, function(x) x + xlab("") + ylab(""))


#layout of plots

lay <- rbind(c(1,2),c(1,2),
              c(3,3))



#arrange the grid and specify the `layout_matrix`
gridExtra::grid.arrange(grobs=p_no_labels, layout_matrix=lay)

enter image description here

...