首页 > 解决方案 > 为不同比例的图形创建相同的比例

问题描述

我有一个数据集,我ggplots为每个数据集创建ind了四个不同的图表。我已将这些图表放入一个列表中,然后使用plot_gridfromcowplot获得一个输出,该输出同时显示所有四个图表。我不太确定如何在这里创建一个通用示例。这四个图具有不同的比例,但我希望我的最终产品对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")

标签: rggplot2tidyversecowplot

解决方案


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

  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)

在此处输入图像描述


推荐阅读