0

我正在尝试完成两项任务:

  1. 将共享相同 y 轴的两个图形紧密结合,但一个具有分类 x 轴变量,另一个具有连续 x 轴变量。我想将它们显示为连续的,仅由一条黑色实线隔开(即左图的右边缘和右图的左边缘)。

  2. 自由修改图形的尺寸,以便我可以。扩展左图的 x 轴,以更好地展示数据的分布,以及 ii. 理想化两个数字的大小比例。

以下是我的尝试:


#libraries used:

library(ggplot2)
library(dplyr)

#Pulling in example dataset:

data_1 <- iris

#Building my left figure, which has a continuous x and y axis, and establishing y axis limits to match between the two figures:

object_1 <- ggplot(data_1, aes(x = Sepal.Width, y = Sepal.Length)) + geom_point() + ylim(0, 10)


#Building my second data table:

data_2 <- iris %>% group_by(Species) %>% summarize(av_petal_length = mean(Petal.Length))

#Building my right hand figure, with empty y axis titles and text to provide space to combine the two figures on the left y axis:

object_2 <- ggplot(data_2, aes(x = Species, y = av_petal_length)) + geom_point() + ylim(0, 10) + 
  theme(axis.title.y = element_blank(), 
        axis.text.y = element_blank())

#Attempt to grid.arrange:

grid.arrange(object_1, object_2, nrow = 1)




在此处输入图像描述

如您所见,一个简单的 grid.arrange 并没有将它们完全结合起来。我试图通过在 theme() 下修改 plot.margin() 来修改两个图形中的面板边距,但这需要大量修改,如果图形完全调整大小,两个图形之间的关系可能会失真。是否可以干净地,简单地将这两个图形组合成一个有凝聚力的矩形,用一条线分隔,并手动修改图形的尺寸?

4

1 回答 1

3

下面,我们为左右图使用单独的主题,删除相关的图边距和右图的 y 轴。

我相信你也可以这样做grid.arrange(),但 {patchwork} 也允许你设置图形宽度。

library(ggplot2)
library(dplyr)
library(patchwork)

# As before
data_1 <- iris
object_1 <- ggplot(data_1, aes(x = Sepal.Width, y = Sepal.Length)) + geom_point() + ylim(0, 10)
data_2 <- iris %>% group_by(Species) %>% summarize(av_petal_length = mean(Petal.Length))
object_2 <- ggplot(data_2, aes(x = Species, y = av_petal_length)) + geom_point() + ylim(0, 10)

# Remove relevant margins from theme, including y-axis elements on the right
theme_left  <- theme(plot.margin = margin(5.5, 0, 5.5, 5.5))
theme_right <- theme(plot.margin = margin(5.5, 5.5, 5.5, 0),
                     axis.ticks.length.y = unit(0, "pt"),
                     axis.title.y = element_blank(),
                     axis.text.y  = element_blank()) 

black_line <- annotate("segment", x = Inf, xend = Inf, y = -Inf, yend = Inf, size = 2)

# Patchwork everything together
(object_1 + theme_left + black_line) + 
  (object_2 + theme_right) +
  plot_layout(widths = c(2, 1))

reprex 包于 2022-02-01 创建(v2.0.1)

于 2022-02-01T21:36:03.380 回答