R ggplot2沿geom_段的颜色渐变()

R ggplot2沿geom_段的颜色渐变(),r,ggplot2,visualization,R,Ggplot2,Visualization,我有一组原点和目标坐标,我在它们之间画线段。问题是,我想用颜色来指示线的方向,而不是使用geom_段()提供的箭头。类似蓝色转变成红色的东西,用来指示方向 有没有一种简单的方法可以使用ggplot2实现这一点 示例数据: points <- data.frame(long=runif(100,-122.4154,-122.3491)) points$lat <- runif(100,37.5976,37.6425) points$long2 <- runif(100,-122.

我有一组原点和目标坐标,我在它们之间画线段。问题是,我想用颜色来指示线的方向,而不是使用geom_段()提供的箭头。类似蓝色转变成红色的东西,用来指示方向

有没有一种简单的方法可以使用ggplot2实现这一点

示例数据:

points <- data.frame(long=runif(100,-122.4154,-122.3491))
points$lat <- runif(100,37.5976,37.6425)
points$long2 <- runif(100,-122.4154,-122.3491)
points$lat2 <- runif(100,37.5976,37.6425)

# add distance
library(geosphere)
points$miles <- apply(points, 1, 
  function(x) distHaversine(p1=c(x["long"],x["lat"]),p2=c(x["long2"],x["lat2"]),r=3959))

我可以通过使用点编号在起点和终点之间插入一组点,然后根据中间点的编号使用渐变对线段着色来实现这一点:

ggplot(points,aes(x=long,xend=long2,y=lat,yend=lat2,color=miles)) + 
  geom_segment() + 
  scale_color_gradient2(low="red",high="blue",midpoint=median(points$miles))
例如:

# generate data points
points <- data.frame(long=runif(100,-122.4154,-122.3491))
points$lat <- runif(100,37.5976,37.6425)
points$long2 <- runif(100,-122.4154,-122.3491)
points$lat2 <- runif(100,37.5976,37.6425)

# function returns a data frame with interpolated points in between start and end point
interp_points <- function (data) {

  df <- data.frame(line_id=c(),long=c(),lat=c())

  for (i in 1:nrow(data)) { 

    line <- data[i,]

    # interpolate lats and longs in between the two
    longseq <- seq(
                    as.numeric(line["long"]),
                    as.numeric(line["long2"]),
                    as.numeric((line["long2"] - line["long"])/10)
                  )
    latseq <- seq(
                    as.numeric(line["lat"]),
                    as.numeric(line["lat2"]),
                    as.numeric(line["lat2"] - line["lat"])/10
                  )

    for (j in 1:10) {
      df <- rbind(df,data.frame(line_id=i,long=longseq[j],lat=latseq[j],seg_num=j))
    }
  }

  df
}

# run data through function
output <- interp_points(points)

# plot the output
ggplot(output,aes(x=long,y=lat,group=line_id,color=seg_num)) + 
  geom_path(alpha=0.4,size=1) +
  scale_color_gradient(high="red",low="blue")
#生成数据点

我认为这不会很容易;你可能必须想出一种方法,在你的细分市场中引入中间点。问了一个类似的问题……这是在“plotrix”软件包的基本图形中实现的。您可以尝试搜索查看是否有人在Rhelp中发布了网格黑客。我以为我在野外见过这样一种动物,但我不是一个特别熟练的ggplot黑客,所以我不想去寻找这种动物。一种可能是用颜色渐变绘制密集的点。