0
votes

I'm making a plot of 2D random walk using R and ggplot2 library. It works, but I would like to show where the starting point and ending point are in my random walk plot.

I tried to create another geom_point and append it to the existing ggplot but it did not work. Any suggestions? Thanks!

x = 0
y = 0
vec1 <- vector()
xcor <- vector()
ycor <- vector()
number = 1000
list_num = c(1,2,3,4)
move = sample(list_num, size = number, replace = TRUE)

for (i in 1:number) {
  if (move[i] == 1) {
    x = x + 1
  }
  else if (move[i] == 2) {
    x = x - 1
  }
  else if (move[i] == 3) {
    y = y + 1
  }
  else if (move[i] == 4) {
    y = y - 1
  }
  vec1 <- c(vec1, i)
  xcor <- c(xcor, x)
  ycor <- c(ycor, y)

} 
df_randomwalk = data.frame(vec1, xcor, ycor)

ggplot(df_randomwalk, aes(x = xcor, y = ycor)) + 
  geom_point(alpha = 0.1, size = 0.3) + geom_path() + 
  theme_minimal() 
1

1 Answers

0
votes

This should do it.

start <- df_randomwalk %>% filter(vec1 == min(df_randomwalk$vec1))
end <- df_randomwalk %>% filter(vec1 == max(df_randomwalk$vec1))

ggplot(df_randomwalk, aes(x = xcor, y = ycor)) + 
  geom_point(alpha = 0.1, size = 0.3) + geom_path() + 
  geom_point(alpha = 0.1, size = 0.3) + 
  theme_minimal() +
  geom_point(start, mapping=aes(x=xcor,y=ycor), colour="red", size=1) +
  geom_point(end, mapping=aes(x=xcor,y=ycor), colour="blue", size=1)