Размещение легенды с использованием plot_grid коровьего сюжета

Я пытаюсь разместить легенду под plot_grid, но она появляется справа от них. Я думал, что позиция регулируется theme(legend.position = 'bottom') в заявлении get_legend(...). Что я делаю неправильно?

Пример кода для воспроизведения:

x = seq(0,10,1)
y = x
z = sqrt(x)
v = log(x+1)

dat = data.frame(x,y)


p1 <- ggplot(dat) + theme_minimal(base_size = 16) + labs(x = 'x', y = 'f(x)') + 
  geom_line(aes(y=y, x=x, linetype = 'A'), color = 'black', size = 1) + 
  geom_line(aes(y=z, x=x, linetype = 'B'), color = 'black', size = 1) + 
  geom_line(aes(y=v, x=x, linetype = 'C'), color = 'black', size = 1) + 
  scale_linetype_manual(values = c(
    'A' = 'solid',
    'B' = 'dashed',
    'C' = 'twodash')) + 
  labs(linetype = 'f') +
  theme(legend.key.width = unit(1.5, 'cm'), legend.position = 'bottom', aspect.ratio = 1)


p2 <- ggplot(dat) + theme_minimal(base_size = 16) + labs(x = 'x', y = 'f(x)') + 
  geom_line(aes(y=y, x=x, linetype = 'A'), color = 'black', size = 1) + 
  geom_line(aes(y=z, x=x, linetype = 'B'), color = 'black', size = 1) + 
  geom_line(aes(y=v, x=x, linetype = 'C'), color = 'black', size = 1) + 
  scale_linetype_manual(values = c(
    'A' = 'solid',
    'B' = 'dashed',
    'C' = 'twodash')) + 
  theme(legend.position = 'none', aspect.ratio = 1)


legend <- get_legend(p1 + theme(legend.position = 'bottom'))
plot_grid(p1 + theme(legend.position = 'none'), p2, legend, labels = c('1', '2'), nrow = 1)

введите здесь описание изображения


person Stefan Hansen    schedule 30.04.2020    source источник


Ответы (1)


Это должно делать то, что вы хотите:

# your code above
# you'd put the plots in two rows, to have the third in the bottom
library(cowplot)
library(ggplot2)
plot_grid(p1 + theme(legend.position = 'none'),
          p2,
          legend, labels = c('1', '2'), nrow = 2 )

введите здесь описание изображения

Вы также можете попробовать это:

bottom_row <- plot_grid(legend)
upper_row <- plot_grid(p1+ theme(legend.position = 'none'), p2, ncol =2, labels = c('1', '2'))
plot_grid(upper_row,
         bottom_row, 
        labels = c('',''), label_size = 12, ncol = 1, rel_heights = c(5,1))

введите здесь описание изображения

person s__    schedule 30.04.2020
comment
Ах, не знал, что в легенде должен быть отдельный ряд. Спасибо за ответ! - person Stefan Hansen; 30.04.2020