I’ve been in to more than a few states. I thought It would be interesting using NetworkX and a mapping plugin to visualize it. I found package call basemap.
Tools I’am using.
- Basemap: Basemap is a toolkit for Matplotlib that provides functionalities to create and visualize geographical maps. It offers various map projections, tools to draw coastlines, countries, and other geographical features, and can also plot data on these maps. Basemap is useful for a wide range of applications, from visualizing geospatial data to creating custom map visualizations.
- networkx: NetworkX is a Python library designed for the creation, manipulation, and study of complex networks of nodes and edges. It provides tools to work with both undirected and directed graphs, supports a variety of graph algorithms, and facilitates easy visualization. NetworkX is commonly used in network analysis, social network analysis, and other applications that involve studying relationships between entities.
- Python – A popular programming language.
import matplotlib.pyplot as plt
import networkx as nx
from mpl_toolkits.basemap import Basemap
# Create a new map using Basemap
m = Basemap(projection='merc', llcrnrlat=24, urcrnrlat=50,
llcrnrlon=-125, urcrnrlon=-66, lat_ts=20, resolution='i')
m.drawcountries()
m.drawstates()
m.drawcoastlines()
m.drawmapboundary(fill_color='#A6CAE0')
m.fillcontinents(color='white', lake_color='#A6CAE0')
# Define the locations
locations = {
"Georgia": (-83.6431, 32.1656),
"Illinois": (-89.3985, 40.6331),
"New York City": (-74.0060, 40.7128),
"Connecticut": (-73.0877, 41.6032),
"New Jersey": (-74.4057, 40.0583),
"Delaware": (-75.5277, 38.9108),
"Maryland": (-76.6413, 39.0458),
"Virginia": (-78.6569, 37.4316),
"South Carolina": (-81.1637, 33.8361),
"Alabama": (-86.7911, 32.3182),
"Florida": (-81.5158, 27.9944),
"Washington DC": (-77.0369, 38.9072),
"Washington": (-120.7401, 47.7511)
}
# Convert the latitudes and longitudes to x and y coordinates
xy = {city: m(lon, lat) for city, (lon, lat) in locations.items()}
# Create a graph using NetworkX
G = nx.Graph()
# Add nodes for each location
for city in locations:
G.add_node(city)
# Add edges connecting each location to the next
cities = list(locations.keys())
for i in range(len(cities)-1):
G.add_edge(cities[i], cities[i+1])
# Draw the nodes and edges
nx.draw_networkx(G, pos=xy, node_size=100, node_color="red", font_size=8)
plt.title("Graph connecting various cities and states")
plt.show()
Here how the image looks like.