2013-07-19 5 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-hacker가 아니기 때문에이 동물을 찾기는 어렵다. –

+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

관련 문제