Stefan Hansen
Stefan Hansen

Reputation: 631

Placement of legend using plot_grid of cowplot

I am trying to place the legend below a plot_grid but it just appears to the right of them. I thought the position was governed by the theme(legend.position = 'bottom') in the get_legend(...) statement. What am I doing wrong?

Example code to reproduce:

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)

enter image description here

Upvotes: 2

Views: 2806

Answers (1)

s__
s__

Reputation: 9485

This should do what you want:

# 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 )

enter image description here

You can also try this:

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))

enter image description here

Upvotes: 3

Related Questions