【问题标题】:Mark start point and end point in ggplot在ggplot中标记起点和终点
【发布时间】:2019-08-27 13:15:42
【问题描述】:

我正在使用 R 和 ggplot2 库制作二维随机游走图。它有效,但我想在我的随机游走图中显示起点和终点在哪里。

我尝试创建另一个 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() 

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    应该这样做。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-04
      • 2021-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      相关资源
      最近更新 更多