2013-07-19 80 views
6

我有一组原点和目标坐标,我在它们之间绘制线段。事情是,我想用颜色来代替线条的方向,而不是geom_segment()提供的箭头。像蓝色过渡到红色,以指示方向。沿着geom_segment()的ggplot2颜色渐变()

有没有简单的方法来做到这一点与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)) 
+1

我不认为这会很容易;您可能不得不采取一种方法将中间点引入您的细分受众群。 http://stackoverflow.com/questions/15924159/smooth-colors-in-geom-line问一个类似的问题...... –

+0

这是在'plotrix'包中的基本图形中实现的。您可以尝试搜索,看看是否有人在Rhelp上发布过网格黑客。我以为我曾经在野外看到过这样的动物,但我不是一个特别熟练的ggplot黑客,所以我不在寻找这种动物。 –

+0

一个黑客可能会用颜色渐变来绘制紧密间隔的点。 –

回答

5

我能够通过在起点和终点之间插一束点与点的号码,然后着色来实现这一使用基于点之间的点数的渐变线段:

例如:

# 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") 

不幸的是,当我用真实的数据,结果没有,因为我是在我的脑海中想象它看起来引人注目!

enter image description here