2

如何对齐具有不同宽度的两个图,以便:

  • 他们的 x 轴是同步的
  • 顶行还包含一个常见的图例

我基本上希望每个 x 轴间隔对应于两个图上相同的厘米数。我试过这个:

library(cowplot)
library(tidyverse)    
wide_plot =  iris %>% 
    ggplot(aes(x = Sepal.Length, Sepal.Width, color = Species)) + 
      geom_point() + 
      theme(legend.position = "none") + 
      scale_x_continuous(limits = c(0,8))
    narrow_plot =  iris %>% 
    ggplot(aes(x = Sepal.Width, Sepal.Length, color = Species)) + 
      geom_point()  + 
      theme(legend.position = "none") + 
      scale_x_continuous(limits = c(0,5) )

    legend = cowplot::get_legend(ggplot(iris,aes(x = Sepal.Length, Sepal.Width, color = Species)) +  geom_point() )

    plot_grid(plot_grid(narrow_plot, legend), wide_plot, nrow = 2 ) 

这产生了这个情节:

在此处输入图像描述

但是上面的问题是顶部底部图上的 x 轴值不是“同步”的。

我试图修改 cowplot::plot_grid 中的 rel_widths 选项,但我希望有一个更准确的解决方案。

4

2 回答 2

3

我知道这不是您问题的直接答案,但是您是否考虑过为两个图采用相同的 x 范围并将图例放在合适的位置?

library(cowplot)
library(tidyverse)    
wide_plot =  iris %>% 
  ggplot(aes(x = Sepal.Length, Sepal.Width, color = Species)) + 
  geom_point() + 
  theme(legend.position = "none") + 
  scale_x_continuous(limits = c(0,8), labels = scales::number_format(accuracy = 0.1))+
  scale_y_continuous( labels = scales::number_format(accuracy = 0.1)) 
narrow_plot =  iris %>% 
  ggplot(aes(x = Sepal.Width, Sepal.Length, color = Species)) + 
  geom_point()  + 
  theme(legend.position = c(0.9,0.7), legend.background = element_rect(size = 30)) + 
  scale_x_continuous(limits = c(0,8), labels = scales::number_format(accuracy = 0.1))+
  scale_y_continuous( labels = scales::number_format(accuracy = 0.1)) 

legend = cowplot::get_legend(ggplot(iris,aes(x = Sepal.Length, Sepal.Width, color = Species)) +  geom_point())

plot_grid(narrow_plot, wide_plot, nrow = 2) 

在此处输入图像描述

于 2020-05-12T12:07:28.130 回答
2

您可以调整边距和轴比例以使图对齐:

wide_plot =  iris %>% 
    ggplot(aes(x = Sepal.Length, Sepal.Width, color = Species)) + 
      geom_point() + 
      theme(legend.position = "none", 
            plot.margin = unit(c(5.5, 140, 5.5, 0), "pt")) +
      scale_y_continuous(limits = c(1, 5)) +
      scale_x_continuous(limits = c(0, 8))

在此处输入图像描述

于 2020-05-12T11:38:20.050 回答