Skip to content

Instantly share code, notes, and snippets.

@rich-iannone
Created October 5, 2015 07:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rich-iannone/4da690cca81757f44f37 to your computer and use it in GitHub Desktop.
Save rich-iannone/4da690cca81757f44f37 to your computer and use it in GitHub Desktop.
Demonstration code for plotting a graph of world cities along with country borders with the DiagrammeR R package.
# Installation
#install.packages("devtools")
devtools::install_github("rich-iannone/DiagrammeR")
library(DiagrammeR)
# Create a graph of border coordinates
country_graph <- country_graph()
# Read in a CSV with location and population data for cities all over the world
world_cities <-
read.csv(system.file("examples/world_cities.csv",
package = "DiagrammeR"),
na.strings = "NANA",
header = TRUE,
stringsAsFactors = FALSE)
# Subset the data frame so that only cities with populations greater than
# 500,000 people remain
population_cities <- subset(world_cities, population > 500000)
# Create a node data frame with cities and their coordinates
city_nodes <-
create_nodes(nodes = 1:nrow(population_cities),
x = population_cities$longitude * 40,
y = population_cities$latitude * 40,
group = population_cities$country_code,
type = "city",
shape = "diamond")
# Add random edges between cities
city_edges <-
create_edges(from = sample(city_nodes$nodes,
nrow(population_cities)),
to = sample(city_nodes$nodes,
nrow(population_cities)),
color = "lightgreen",
width = 2)
# Make a city graph
city_graph <- create_graph(nodes_df = city_nodes,
edges_df = city_edges)
# Combine the city graph with the country graph
combined_graph <- combine_graphs(country_graph, city_graph)
# Render the cities along with the countries
render_graph(combined_graph, output = "visNetwork")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment