Last active
September 9, 2023 23:55
-
-
Save rich-iannone/fefe7444da93da08b6fa to your computer and use it in GitHub Desktop.
Demonstration code for plotting a graph of US cities along with country borders with the DiagrammeR R package.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Installation | |
#install.packages("devtools") | |
devtools::install_github("rich-iannone/DiagrammeR") | |
library(DiagrammeR) | |
# Create a graph of border coordinates for USA, Canada, and Mexico | |
country_graph <- country_graph(iso_a2 = c("US", "CA", "MX")) | |
# Read in a CSV with US city data | |
us_cities <- | |
read.csv(system.file("examples/us_cities.csv", | |
package = "DiagrammeR"), | |
header = TRUE, stringsAsFactors = FALSE) | |
# Subset the data frame so that only cities with populations greater than | |
# 100,000 people remain | |
population_us_cities <- subset(us_cities, Population > 100000) | |
# Add the cities and their coordinates | |
city_nodes <- | |
create_nodes(nodes = 1:nrow(population_us_cities), | |
x = population_us_cities$Longitude * 40, | |
y = population_us_cities$Latitude * 40, | |
group = population_us_cities$Region, | |
width = 1, | |
type = "city", | |
shape = "circle") | |
# Add random edges between cities | |
city_edges <- | |
create_edges(from = sample(city_nodes$nodes, | |
nrow(population_us_cities)), | |
to = sample(city_nodes$nodes, | |
nrow(population_us_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