首页 > 解决方案 > 在 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 选项,但我希望有一个更准确的解决方案。

标签: rggplot2cowplotpatchwork

解决方案


我知道这不是您问题的直接答案,但是您是否考虑过为两个图采用相同的 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) 

在此处输入图像描述


推荐阅读