在ggplot中标记起点和终点

时间:2019-04-05 15:20:55

标签: r ggplot2

我正在使用R和ggplot2库绘制2D随机游动图。它可以工作,但是我想显示起点和终点在我的随机步行图中的位置。

我试图创建另一个geom_point并将其附加到现有的ggplot中,但是它不起作用。有什么建议么?谢谢!

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 个答案:

答案 0 :(得分:0)

这应该做到。

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)