对于不使用绘图功能的循环
我正在尝试一种方法来弄清楚我如何一次用for循环打印多个图,因为我非常陌生,我似乎找不到一种方法,
我有40个原则组件我想要绘制循环的绘制,但我只能通过每次调用功能来单独进行操作;因为循环仅在下面什么都不做
就是显示或绘制原理组件的函数
showPrincipalComponents <- function(PCNumber) {
tidied_pca %>%
filter(PC == PCNumber) %>%
top_n(11, abs(Contribution)) %>%
mutate(Tag = reorder(Tag, Contribution)) %>%
ggplot(aes(Tag, Contribution, fill = Tag)) +
geom_col(show.legend = FALSE, alpha = 0.8) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5),
axis.ticks.x = element_blank()) +
labs(x = "Personal attributes",
y = "Principal Component Importance")
}}
这项工作:
showPrincipalComponents(comp[1])
showPrincipalComponents(comp[2])
showPrincipalComponents(comp[3])
showPrincipalComponents(comp[4])
这不是(如果不返回任何东西执行):
x=1:40
for (i in x){showPrincipalComponents(comp[i])}
任何帮助都将不胜感激
I Am trying out a way to figure out how i could print multiple plots at once with a for loop , as i am super new to R i can't seem to find a way to do this
I Have 40 Principle components that i would like to plot through for loop, but i can only do it individually by calling the function every time ; for loop just does nothing
Below is the function to show or plot principle components
showPrincipalComponents <- function(PCNumber) {
tidied_pca %>%
filter(PC == PCNumber) %>%
top_n(11, abs(Contribution)) %>%
mutate(Tag = reorder(Tag, Contribution)) %>%
ggplot(aes(Tag, Contribution, fill = Tag)) +
geom_col(show.legend = FALSE, alpha = 0.8) +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5),
axis.ticks.x = element_blank()) +
labs(x = "Personal attributes",
y = "Principal Component Importance")
}
This Works:
showPrincipalComponents(comp[1])
showPrincipalComponents(comp[2])
showPrincipalComponents(comp[3])
showPrincipalComponents(comp[4])
This Does Not(executes without returning anything):
x=1:40
for (i in x){showPrincipalComponents(comp[i])}
Any Help would be appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须做两件事,以使其在循环的
中起作用。
(1)正如@NeilFWS在注释中已经指出的那样,需要对循环的
输出进行插入(例如
out [[i]]&lt; -
)。(2)由于
ggplot
使用懒惰评估仅执行(1)将产生相同的图40次(始终是最后一个图,i = 40
)。如果要坚持使用循环而不是lapply
,则可以将函数调用包装到eval(bquote())
并进行评估<代码>。(i)。You have to do two things to make it work in a
for
loop.(1) As @neilfws already points out in the comments, the output of the
for
loop needs to be assiged (e.g.out[[i]] <-
).(2) Since
ggplot
uses lazy evaluation only doing (1) will yield the same plot forty times (always the last plot,i = 40
). If you want to stick to afor
loop instead of anlapply
you could wrap the function call intoeval(bquote())
and evaluate.(i)
.