user9059916
user9059916

Reputation: 13

How to draw a chain network map

I want a central warehouse-customer supply chain network. I am trying to plot 394 cities with connecting lines. But I received an error message. I am using the following code. Note that my data frame contains latitude, longitude of the cities. Origin is a same place, whereas a destination changes every row.

map <-get_map(location='united states', zoom=4, maptype = "satellite",
             source='google',color='color')
p <- ggmap(map)

    for(i in 2:nrow(x))

    {
      plot_data <-as.data.frame(rbind(c(unique(x$Origin),as.numeric(unique(x$LAT.x)),as.numeric(unique(x$LONG.x))),
                                       c(x$Destination[i],x$LAT.y[i],x$LONG.y[i])))

      colnames(plot_data) <- c("Place","Lat","Long")
      plot_data$Lat <- as.numeric(as.character(plot_data$Lat))
      plot_data$Long <- as.numeric(as.character(plot_data$Long))

      p <- p + geom_point(data=plot_data, aes(x=Long, y=Lat),color="blue",size=3)
      p <- p + geom_path(data=plot_data, aes(x=Long, y=Lat), color="red", size=1)

      }

Upvotes: 1

Views: 202

Answers (1)

jazzurro
jazzurro

Reputation: 23574

I leave a demonstration showing how I usually handle this kind of task. I borrowed a data set from the maps package. There is long/lat information for world cities. I subsetted some of the data focusing on the US. I added two columns to this object. One is for long and the other is for lat for a starting point of lines. In this case, I randomly chose Denver. I used great circle to get lines between Denver and destination cities. Then, I converted the data to data.frame so that ggplot can draw a map using fortify().

library(ggmap)
library(maps)
library(dplyr)
library(ggplot2)
library(geosphere)

data(world.cities)

mymap <- get_map(location = "texas", maptype = "watercolor", source = "stamen", zoom = 4)

foo <- world.cities %>%
       filter(pop >= 500000 & country.etc == "USA") %>% 
       mutate(start_long = -104.9903,
              start_lat = 39.7392) %>%
       do(fortify(as(gcIntermediate(.[,c("start_long", "start_lat")],
                                    .[,c("long", "lat")],
                                    100,
                                    breakAtDateLine = FALSE,
                                    addStartEnd = TRUE,
                                    sp = TRUE), "SpatialLinesDataFrame")))

g <- ggmap(mymap) +
     geom_path(data = foo, aes(x = long, y = lat, group = id), color = "red")

enter image description here

Upvotes: 1

Related Questions