为具有不同比例的图形创建相同的比例

Creating the same scale for graphs with different scales

我有一个数据集,我在其中为每个 ind 创建了 ggplots,最终我得到了四个不同的图表。我已将这些图表放入一个列表中,然后使用 cowplot 中的 plot_grid 获得同时显示所有四个图表的单个输出。我不太确定如何创建一个通用示例 here.The 四个图形具有不同的比例,但我希望我的最终产品对 plot_grid 输出中的每个图形具有相同的比例。我该怎么做?

这是一个示例数据集:

library(ggplot2)
data(iris)
rsq <- lapply(1:length(unique(iris$Species)), function(i) {
  cor(iris[iris$Species == unique(iris$Species)[i], "Sepal.Length"], iris[iris$Species == unique(iris$Species)[i], "Petal.Length"])^2
})

p.list <- lapply(1:length(unique(iris$Species)), function(i) {
  ggplot(iris[iris$Species == unique(iris$Species)[i], ], aes(x = Sepal.Length, y = Petal.Length)) +
    geom_point() + theme_bw()+
    geom_text(aes(x=min(Sepal.Length),y=max(Petal.Length),label=paste0("R= ",round(rsq[[i]],2))))
})

cowplot::plot_grid(plotlist = p.list[1:3], nrow = 1, ncol = 3, 
                   labels = "AUTO")

至少有两个选项可以达到您想要的结果。

  1. 如果您想坚持使用 plot.grid,您可以通过在每个绘图中为 x 和 y 比例设置相同的限制来实现您想要的结果。为此计算数据中的整体最小值和最大值:
library(ggplot2)

rsq <- lapply(1:length(unique(iris$Species)), function(i) {
  cor(iris[iris$Species == unique(iris$Species)[i], "Sepal.Length"], iris[iris$Species == unique(iris$Species)[i], "Petal.Length"])^2
})

d_list <- split(iris, iris$Species)

xmin <- min(unlist(lapply(d_list, function(x) min(x["Sepal.Length"]))))
xmax <- max(unlist(lapply(d_list, function(x) max(x["Sepal.Length"]))))
ymin <- min(unlist(lapply(d_list, function(x) min(x["Petal.Length"]))))
ymax <- max(unlist(lapply(d_list, function(x) max(x["Petal.Length"]))))

p.list <- lapply(1:length(unique(iris$Species)), function(i) {
  ggplot(iris[iris$Species == unique(iris$Species)[i], ], aes(x = Sepal.Length, y = Petal.Length)) +
    geom_point() +
    scale_x_continuous(limits = c(xmin, xmax)) +
    scale_y_continuous(limits = c(ymin, ymax)) +
    theme_bw() +
    geom_text(aes(x = min(Sepal.Length), y = max(Petal.Length), label = paste0("R= ", round(rsq[[i]], 2))))
})

cowplot::plot_grid(
  plotlist = p.list[1:3], nrow = 1, ncol = 3,
  labels = "AUTO"
) 

  1. 作为第二种方法,您可以使用我在评论中提到的分面。为此,将您的数据集绑定为一个并添加一个 id 变量。此外,还将 r 方值也放入数据框中。这样做可以让你使用分面来制作你的情节:
library(ggplot2)
library(dplyr)

d_list <- split(iris, iris$Species)

rsq_list <- lapply(d_list, function(x) {
  data.frame(
    rsq = cor(x["Sepal.Length"], x["Petal.Length"])[1, 1]^2,
    Sepal.Length = min(x["Sepal.Length"]),
    Petal.Length = max(x["Petal.Length"])
  )
})

d_bind <- dplyr::bind_rows(d_list)
rsq_bind <- dplyr::bind_rows(rsq_list, .id = "Species")

ggplot(d_bind, aes(x = Sepal.Length, y = Petal.Length)) +
  geom_point() +
  theme_bw() +
  geom_text(data = rsq_bind, aes(label = paste0("R= ", round(rsq, 2)))) +
  facet_wrap(~Species)