使用 for 循环 (R) 更新 ggplot [英] Update a ggplot using a for loop (R)

查看:30
本文介绍了使用 for 循环 (R) 更新 ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在更新 ggplot 对象时遇到了一些问题.我想要做的是在我在每个循环中更改的特定位置放置一条垂直线,因此:多条线将显示在不同的位置.但是,当我使用 for 循环时,它只显示它创建的最后一行,但是当我手动执行它时,它可以工作.我创建了一个可复制的示例,你们可以检查:

I am having some problems updating a ggplot object. What I want to do is to put a vertical line in a specific location that I change on every loop, hence: multiple lines will be displayed in different locations. However, when I use a for loop it only shows me the last line that it's created but when I do it manually it works. I created a reproductible example that you guys can check:

library(ggplot2)

x <- ggplot(mapping = aes(x = 1:100, y = 1:100)) +
  geom_line()

for(i in 1:6){
  x <- x + geom_vline(aes(xintercept = i*5))
}

y <- ggplot(mapping = aes(x = 1:100, y = 1:100)) +
  geom_line()

y <- y + geom_vline(aes(xintercept = 5))
y <- y + geom_vline(aes(xintercept = 10))
y <- y + geom_vline(aes(xintercept = 15))
y <- y + geom_vline(aes(xintercept = 20))
y <- y + geom_vline(aes(xintercept = 25))
y <- y + geom_vline(aes(xintercept = 30))

检查两个图.为什么第一个情节看起来与第二个不同,尽管对我来说两个过程都做相同"的事情?

Check both plots. Why is the first plot not looking the same as the second one, although for me both processes do the "same" thing?

推荐答案

我在看一些人留给我的一些贡献,有一个非常有效地解决了它,它是使用 aes_() 而不是 aes().不同之处在于 aes_() 强制评估和更新绘图,而 aes() 仅在绘制绘图时评估索引.因此:它在 for 循环内时永远不会更新.

I was looking at some contributions that some people left me and there is one who solves it pretty efficiently and it is to use aes_() instead of aes(). The difference is that aes_() forces to evaluate and update the plot, while aes() only evaluates the indexes when the plot is drawn. Hence: it never updates while it is inside a for loop.

library(ggplot2)

x <- ggplot(mapping = aes(x = 1:100, y = 1:100)) +
  geom_line()

for(i in 1:6){
  x <- x + geom_vline(aes_(xintercept = i*5))
}

这篇关于使用 for 循环 (R) 更新 ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆