[英]How to add to ggplot2 plot inside of for loop
I'm trying to plot multiple circles of different sizes on a plot using ggplot2's geom_point inside of a for loop.我正在尝试在 for 循环中使用 ggplot2 的 geom_point 在 plot 上 plot 多个不同大小的圆圈。 Every time I run it though, it plots all the circles, but all in the location of the last circle instead of in their respective locations as given by the data frame.
每次我运行它时,它都会绘制所有圆圈,但都在最后一个圆圈的位置,而不是在数据框给出的各自位置。 Below is an example of the code I am running.
下面是我正在运行的代码示例。 I'm wondering how I would fix this or if there's a better way to get at what I'm trying to do here.
我想知道如何解决这个问题,或者是否有更好的方法来完成我在这里尝试做的事情。
data <- data.frame("x" = c(0, 500, 1000, 1500, 2000),
"y" = c(1500, 500, 2000, 0, 1000),
"size" = c(3, 5, 1.5, 4.2, 2.6)
)
g <- ggplot(data = data, aes(x = x, y = y)) + xlim(0,2000) + ylim(0,2000)
for(i in 1:5) {
g <- g + geom_point(aes(x=data$x[i],y=data$y[i]), size = data$size[i], pch = 1)
}
print(g)
It's pretty rare to need a for-loop for a plot -- ggplot2 will take the whole dataframe and process it all without you needing to manage each row.很少需要 plot 的 for 循环 - ggplot2 将占用整个 dataframe 并处理它,而无需管理每一行。
ggplot(data = data, aes(x = x, y = y, size = size)) +
geom_point(pch = 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.