R 在循环中动态命名变量以创建30个GGPLOT
我有一个包含30列的数据框,我想基于这些列创建30个(gg)图。通过ggplot创建绘图时,必须创建一个变量,将绘图的所有信息添加到该变量中 有没有办法在for循环中创建30个这样的变量名(这样我就不必在本地创建和存储它们) 在前面的代码中,我重复了以下步骤30次: 在前面的代码中,我有以下内容:R 在循环中动态命名变量以创建30个GGPLOT,r,ggplot2,R,Ggplot2,我有一个包含30列的数据框,我想基于这些列创建30个(gg)图。通过ggplot创建绘图时,必须创建一个变量,将绘图的所有信息添加到该变量中 有没有办法在for循环中创建30个这样的变量名(这样我就不必在本地创建和存储它们) 在前面的代码中,我重复了以下步骤30次: 在前面的代码中,我有以下内容: a1 = ggplot(data = results_round_one, aes(results_round_one$`R-0,01`)) a1 = a1 + geom_h
a1 = ggplot(data = results_round_one,
aes(results_round_one$`R-0,01`))
a1 = a1 + geom_histogram()
a1 = a1 + xlim(0.46, 0.55)
a1 = a1 + geom_vline(xintercept= mean(results_round_one$`R-0,01`),
col = 'blue')
a1 = a1 + geom_vline(xintercept = max(results_round_one$`R-0,01`),
col = 'red')
a1= a1 + labs(y = 'Frequency',
x= 'Validated accuracy',
title = 'Optimizer = RMSProp',
subtitle = 'Learning rate = 0.01')
但是,由于我只需要更改aes和标签,我认为我也应该能够在for循环中执行此过程。您可以应用直方图函数:
getImage <- function(col){
a1 = ggplot(data = results_round_one,
aes(results_round_one[, col])) +
geom_histogram() +
xlim(0.46, 0.55) +
geom_vline(xintercept= mean(results_round_one[, col]),
col = 'blue') +
labs(y = 'Frequency',
x= 'Validated accuracy',
title = 'Optimizer = RMSProp',
subtitle = 'Learning rate = 0.01')
return(a1)
}
这将生成不同的图。在缺少一些示例数据的情况下,下面是一些代码,可以循环通过
iris
列,创建密度图:
library(purrr)
library(dplyr)
df <- iris %>%
select(Sepal.Length:Petal.Width)
df %>%
map2(names(df), ~ .x %>%
as.data.frame %>%
set_names(.y) %>%
ggplot(aes_string(.y)) + geom_density() + ggtitle(.y))
你能为你的想法提供一个简单的例子吗?在你的例子中变量(
a1
)而且频繁的重新分配根本没有必要,实际上有点混乱。此外,使用aes
会产生微妙的次优结果。最好将aes\u字符串
与列名称一起使用。我建议使用@see-king\u of_knowledge绝对没有理由使用e> @KonradRudolph,是的,我很想听到一个合理的动机,为什么赋值运算符比等式符号好。@KonradRudolph,我同意在这种情况下,它不会有什么区别,除了一致性之外,实际上是无关紧要的。但是,可以找到细微的区别
library(purrr)
library(dplyr)
df <- iris %>%
select(Sepal.Length:Petal.Width)
df %>%
map2(names(df), ~ .x %>%
as.data.frame %>%
set_names(.y) %>%
ggplot(aes_string(.y)) + geom_density() + ggtitle(.y))
results_round_one %>%
map2(names(results_round_one), ~ .x %>%
as.data.frame %>%
set_names(.y) %>%
ggplot(aes_string(.y)) +
geom_histogram() +
xlim(0.46, 0.55) +
geom_vline(xintercept = mean(.x), col = 'blue') +
geom_vline(xintercept = max(.x), col = 'red') +
labs(y = 'Frequency',
x= 'Validated accuracy',
title = 'Optimizer = RMSProp',
subtitle = 'Learning rate = 0.01'))