0

Is there a way to name this plot (map). It is created with over multiple lines and even a loop. I'd like to name it so I can use it with cowplot or grid arrange.

 #create basemap
    maps::map("world", regions=c("usa"), fill=T, col="#898f9c", bg="transparent", ylim=c(21.0,50.0), xlim=c(-130.0,-65.0))
    points(acities$Longitude, acities$Latitude, pch=7, cex=1, col="#e9ebee")


    for (i in (1:dim(acitiesc)[1])) { 

      inter <- geosphere::gcIntermediate(c(acitiesc$destLon[i], acitiesc$destLat[i]), c(acitiesc$Longitude[i], acitiesc$Latitude[i]), n=500)
      lines(inter, lwd=0.5, col="#29487d", lty=1)

    }

I could also create an image if that's easer, but the end use will be a reactive plot for a shiny app, so it will need to respond to user inputs.

Thank you.

Jdv
  • 329
  • 1
  • 10
  • Unfortunately I can't. But this post has a similar example of how my plot was created https://www.gis-blog.com/flight-connection-map-with-r/ – Jdv Jun 06 '20 at 17:06

1 Answers1

1

You can use as.grob of the ggplotify package as follows.

library(nycflights13)
library(dplyr)
library(ggplotify)
library(grid)
usairports <- filter(as.data.frame(airports), lat < 48.5)
usairports <- filter(usairports, lon > -130)
usairports <- filter(usairports, faa!="JFK") 
jfk <- filter(airports, faa=="JFK")

myplot <- function(data, ref) {
  maps::map("world", regions=c("usa"), fill=T, col="#898f9c", 
            bg="transparent", ylim=c(21.0,50.0), xlim=c(-130.0,-65.0))
  points(data$lon, data$lat, pch=7, cex=1, col="#e9ebee")
  for (i in 1:nrow(data)) { 
    inter <- geosphere::gcIntermediate(c(ref$lon[1], ref$lat[1]), 
                              c(data$lon[i], data$lat[i]), n=500)
    lines(inter, lwd=0.5, col="#29487d", lty=1)
  }
}

p1 <- as.grob(~myplot(usairports, jfk))
grid.draw(p1)

p1 is a grob and can be combined with a ggplot object using grid.arrange as follows:

p2 <- ggplot(data=usairports, aes(x=dst)) + geom_bar() + theme_bw()
gridExtra::grid.arrange(p1, p2)

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58