问题描述
我有一个包含30列的数据框,我想基于这些列创建30个(gg)图.通过ggplot创建图时,必须创建一个变量,该图的所有信息都将添加到该变量中.
I have a dataframe with 30 columns and I would like to create 30 (gg)plots based on these columns. When creating a plot through ggplot, you have to create a variable to which all the information of the plot is added.
有没有一种方法可以在for循环中创建30个这样的变量名(这样我就不必在本地创建和存储它们了?
Is there a way how I can create 30 of such variable names in a for loop (so that I don't have to create and store them all locally?
在先前的代码中,我重复了以下步骤30次:
In earlier code I repeated the below steps 30 times:
在以前的代码中,我有以下内容:
In earlier code, I had the following:
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循环中完成此过程.
However, since I only have to change the aes and the labels, I think I should be able to do this process in a for loop as well.
推荐答案
在缺少示例数据的情况下,以下代码将循环遍历iris
列,从而创建密度图:
In absence of some example data, here is some code that would loop through iris
columns, creating density plots:
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))
使用您的代码,类似以下内容:
Using your code, something along the lines of:
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'))
这篇关于在循环中动态命名变量以创建30个ggplots的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!