Ggplot2 color gradient along geom_segment ()

I have a set of origin and destination coordinates, and I draw line segments between them. The fact is, I would like to indicate the direction of the line using color instead of the arrows that are supplied with geom_segment (). Something like blue turning into red to indicate a direction.

Is there an easy way to do this with ggplot2?

Sample data:

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

So far, I could color the lines in different ways, but I have not found a way to have two colors in the same segment of the line and transition between them when I have only the start and end points, without between points:

 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)) 
+6
source share
1 answer

I was able to achieve this by interpolating a bunch of points between the starting and ending points with the point number, and then coloring the segment with a gradient depending on the number of points between them:

Example:

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

Unfortunately, when I used real data, the result did not look as convincing as I imagined!

enter image description here

+5
source

Source: https://habr.com/ru/post/949853/


All Articles