I am trying to output multiple plots in ggplot2
by looping through the plot function.
Let's say I have a dataframe points
with the coordinates for two points. I start by plotting a single point in ggplot2
:
library(ggplot2)
point1 <- c(1,2)
point2 <- c(2,2)
points <-as.data.frame(rbind(point1,point2))
ggplot(data = points, mapping = aes(x = points[, 1], y = points[, 2])) +
geom_point(aes(x = points[1,1], y = points[1,2])) +
xlim(-3, 3) +
ylim(-3, 3) +
theme_bw()
Now I would like to loop over the dataframe so that I can produce two plots, save them in a list, and print them side by side.
I have tried:
library(ggplot2)
point1 <- c(1,2)
point2 <- c(2,2)
points <-as.data.frame(rbind(point1,point2))
point_plots_list <- list()
for (i in 1:nrow(points)) {
p <- ggplot(data = points, mapping = aes(x = points[, 1], y = points[, 2])) +
geom_point(aes(x = points[i, 1], y = points[i, 2])) +
xlim(-3, 3) +
ylim(-3, 3) +
theme_bw()
point_plots_list[[i]] <- p
}
point_plots_list
#> [[1]]
#>
#> [[2]]
Created on 2021-04-09 by the reprex package (v0.3.0)
Question
Why do the two plots look the same?