r - 为不同比例的图形创建相同的比例
问题描述
我有一个数据集,我ggplots
为每个数据集创建ind
了四个不同的图表。我已将这些图表放入一个列表中,然后使用plot_grid
fromcowplot
获得一个输出,该输出同时显示所有四个图表。我不太确定如何在这里创建一个通用示例。这四个图具有不同的比例,但我希望我的最终产品对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")
解决方案
至少有两种选择可以达到您想要的结果。
- 如果您想坚持下去,
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"
)
- 作为第二种方法,您可以使用我在评论中提到的分面。为此,将您的数据集绑定到一个并添加一个 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)
推荐阅读
- node.js - 如何在弹性搜索中插入多个 JSON 文档
- android - 如何在 kotlin 的 android 共享首选项中存储 2D 数组?
- django - 如何使用 PUT 使用 Django REST 框架更新 Vue 中的某些内容
- symfony - --global 选项在做作曲家时不存在 --global 要求
- ios - SplitViewController 只显示白屏
- java - 当有多个参数时,方法引用如何在后台工作
- javascript - 无法使用 fetch 发送多部分,但 axios 工作正常
- tensorflow - 在估算器中同时使用 batch_norm 和 dropout 是否相关?
- php - “client_reference_id”参数未通过
- c# - Unity:敌人物体穿过背景边缘的盒子碰撞器