Search code examples
rggplot2spatialr-sf

ggplot2, spatial map, add a line segment on to the border


Using this as the reference, I want to add a line segment to a section of the border in a spatial map. The code below does add a line segment, but it is horizontal in direction, rather than vertical as desired. Any help in correcting the direction to vertical is very much appreciated.

library(ggplot2)
library(dplyr)
library(sp)
library(sf)
library(raster)

# get the data for the map (map of Karnataka state in India)

    kn_sf <- 
  getData("GADM", country = "IND", level = 2) %>% 
  st_as_sf() %>% 
  filter(NAME_1 == "Karnataka")

# get the latitude and longitude data 
#for plotting the line segment 
#(this segment is intended to show the 
#coastline of Karnataka, on the western
#periphery of the state)

kncoast <- data.frame(orig_lat=12.7571, 
                      orig_lon=74.87461,
                      dest_lat=12.77404,
                      dest_lon=77.16021) 

 # plot the map
kn_sf %>% 
  ggplot()+
  geom_sf()+
  geom_segment(data = kncoast, 
               aes(x = orig_lon,
                   y = orig_lat,
                   xend = dest_lon,
                   yend = dest_lat), 
               color="red", size=1) +  
  coord_sf()

This gives the following map. The line needs to be vertical, and not horizontal. I cannot figure out the source of mistake in my code. enter image description here


Solution

  • The segment simply has the co-ordinates you gave it. A vertical line would be something like this:

    kncoast <- data.frame(orig_lat=12.7571, 
                          orig_lon=74.87461,
                          dest_lat=15,
                          dest_lon=74.87461) 
    

    enter image description here

    If you want the line to stretch across the coast of Karnataka, then something like this would be better:

    kncoast <- data.frame(orig_lat=12.7571, 
                          orig_lon=74.87461,
                          dest_lat=14.75,
                          dest_lon=74.15) 
    

    enter image description here