r - 使用cowplot的plot_grid放置图例

标签 r ggplot2 cowplot

我试图将图例放置在 plot_grid 下面,但它只是出现在它们的右侧。我认为该位置是由 get_legend(...) 语句中的 theme(legend.position = 'bottom') 控制的。我做错了什么?

要重现的示例代码:

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

最佳答案

这应该可以满足您的要求:

# 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

您也可以尝试这个:

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

关于r - 使用cowplot的plot_grid放置图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61517820/

相关文章:

r - magrittr 包中的管道不适用于函数 rm()

R 中的递归编程

r - R 上三个子集的方差分析

r - 按组划分的真/假值计数条形图(斜线图)

r - 如何防止x轴与facet_wrap(~variable)重叠ggplotly

r - 在r中重命名列的循环

r - 在使用 facet_wrap 创建的直方图上绘制均值

r - ggplot2中的分轴图

r - 使用Cowplot时减少地 block 之间的边距

r - 如何使用plot_grid在没有任何空间的情况下放置绘图?