r语言 - 自动将ggplot2中的散点图写入文件夹



我有大量的变量,并希望创建散点图比较所有变量到一个单一的变量。我已经能够使用lapply在基数R中做到这一点,但我无法使用lapplyggplot2中完成相同的任务。

下面是一个示例数据集。

df <- data.frame("ID" = 1:16)
df$A <- c(1,2,3,4,5,6,7,8,9,10,11,12,12,14,15,16)
df$B <- c(5,6,7,8,9,10,13,15,14,15,16,17,18,18,19,20)
df$C <- c(11,12,14,16,10,12,14,16,10,12,14,16,10,12,14,16)

我使用下面的代码定义了我想要生成散点图的变量:

df_col_names <- df %>% select(A:C) %>% colnames(.) 

下面是我如何能够成功地完成针对变量A绘制所有变量的任务,在R中使用lapply:

lapply(df_col_names, function(x) {
tiff(filename=sprintf("C:\Documents\%s.tiff", x),
width = 1000, height = 1000, res=200)
plot(df$A, df[[x]], 
pch=19,
cex = 1.5,
ylab = x,
ylim = c(0, 20),
xlim = c(0, 20))
dev.off()
})

下面是我在ggplot2中完成任务的尝试,但没有成功。它生成tiff图像,尽管它们是空的。

lapply(df_col_names, function(x) {
tiff(filename=sprintf("C:\Documents\%s.tiff", x),
width = 1000, height = 1000, res=200)
ggplot(df) +
geom_point(data = df,
aes(x = A, y = df_col_names[[x]], size = 3)) +
geom_smooth(aes(x = A, y = df_col_names[[x]], size = 0), method = "lm", size=0.5) +
coord_fixed(ratio = 1, xlim = c(0, 20), ylim = c(0, 20)) +
guides(size = FALSE, color = FALSE) +
theme_bw(base_size = 14)
dev.off()
})

它适用于我与ggsave。另外请注意,您正在将字符串列名传递给ggplot,因此使用.data来引用实际的列值。

library(ggplot2)
lapply(df_col_names, function(x) {
ggplot(df) +
geom_point( aes(x = A, y = .data[[x]], size = 3)) +
geom_smooth(aes(x = A, y = .data[[x]], size = 0), method = "lm", size=0.5) +
coord_fixed(ratio = 1, xlim = c(0, 20), ylim = c(0, 20)) +
guides(size = FALSE, color = FALSE) +
theme_bw(base_size = 14) -> plt
ggsave(sprintf("%s.tiff", x), plt)
})

最新更新