• Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
Monday, March 9, 2026
newsaiworld
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us
No Result
View All Result
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us
No Result
View All Result
Morning News
No Result
View All Result
Home Artificial Intelligence

The way to Make Proximity Maps with Python | by Lee Vaughan | Oct, 2024

Admin by Admin
October 30, 2024
in Artificial Intelligence
0
1zgo Lvx0j92q7cd Svytaq.png
0
SHARES
0
VIEWS
Share on FacebookShare on Twitter

READ ALSO

The Information Workforce’s Survival Information for the Subsequent Period of Information

LatentVLA: Latent Reasoning Fashions for Autonomous Driving


Right here’s the total code (written in JupyterLab). I’ll break down the code blocks within the following sections.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import geopandas as gpd
from geopy.distance import great_circle

# SEC faculties with coordinates (coords by ChatGPT4):
information = {
'faculty': ['Alabama', 'LSU', 'Ole Miss', 'Miss State',
'Auburn', 'Arkansas', 'Missouri', 'Vanderbilt',
'Tennessee', 'Florida', 'Georgia', 'Kentucky',
'S. Carolina', 'TAMU', 'Texas', 'Oklahoma'],
'latitude': [33.209, 30.412, 34.365, 33.456,
32.603, 36.068, 38.951, 36.162,
35.960, 29.651, 33.950, 38.049,
34.000, 30.620, 30.284, 35.222],
'longitude': [-87.538, -91.177, -89.526, -88.811,
-85.484, -94.172, -92.328, -86.784,
-83.920, -82.324, -83.377, -84.500,
-81.034, -96.340, -97.740, -97.445]
}

df = pd.DataFrame(information)

# Choose a faculty to plot the gap from.
# Use the identical identify as within the earlier information dict:
SCHOOL = 'Texas'

# Set the grid decision.
# Bigger = larger res and smoother contours:
RESOLUTION = 500

# Get coordinates for SCHOOL:
school_index = df[df['school'] == SCHOOL].index[0]
school_coords = df.loc[school_index, ['latitude', 'longitude']].to_numpy()

# Create grid of factors for interpolation:
x_min, x_max = df['longitude'].min(), df['longitude'].max()
y_min, y_max = df['latitude'].min(), df['latitude'].max()
xx, yy = np.meshgrid(np.linspace(x_min, x_max, RESOLUTION),
np.linspace(y_min, y_max, RESOLUTION))

# Calculate distances from SCHOOL to each level in grid:
distances = np.zeros(xx.form)
for i in vary(xx.form[0]):
for j in vary(xx.form[1]):
point_coords = (yy[i, j], xx[i, j])
distances[i, j] = great_circle(school_coords, point_coords).miles

# Create the color-filled contour map:
fig, ax = plt.subplots(1, 1, figsize=(10, 8))
contour = ax.contourf(xx, yy, distances,
cmap='coolwarm',
alpha=0.9)
cbar = fig.colorbar(contour, ax=ax, shrink=0.7)
cbar.set_label(f'Distance from {SCHOOL} (miles)')
ax.scatter(df['longitude'], df['latitude'], s=2, shade='black')

# Load state boundaries from US Census Bureau:
url = 'https://www2.census.gov/geo/tiger/GENZ2021/shp/cb_2021_us_state_20m.zip'
states = gpd.read_file(url)

# Filter states throughout the map limits:
states = states.cx[x_min:x_max, y_min:y_max]

# Plot the state boundaries:
states.boundary.plot(ax=ax, linewidth=1, edgecolor='black')

# Add labels for the colleges:
for i, faculty in enumerate(df['school']):
ax.annotate(
faculty,
(df['longitude'][i], df['latitude'][i]),
textcoords="offset factors",
xytext=(2, 1),
ha='left',
fontsize=8
)

ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_title(f'Distance from {SCHOOL} to Different SEC Faculties')

# fig.savefig('distance_map.png', dpi=600)
plt.present()

And right here’s the output, displaying the gap from the College of Texas in Austin to the opposite SEC faculties:

A colorful map of distances from the University of Texas in Austin.
Distance from College of Texas to different SEC faculties (by creator)

Importing Libraries

This mission requires NumPy, Matplotlib, pandas, geopandas, geopy, and scipy. You could find set up directions within the hyperlinks.

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import geopandas as gpd
from geopy.distance import great_circle

Loading Knowledge

For the enter information, I made a listing of the colleges after which had ChatGPT produce the dictionary with the lat-lon coordinates. The dictionary was then transformed right into a pandas DataFrame named df.

# SEC faculties with coordinates (coords by ChatGPT4):
information = {
'faculty': ['Alabama', 'LSU', 'Ole Miss', 'Miss State',
'Auburn', 'Arkansas', 'Missouri', 'Vanderbilt',
'Tennessee', 'Florida', 'Georgia', 'Kentucky',
'S. Carolina', 'TAMU', 'Texas', 'Oklahoma'],
'latitude': [33.209, 30.412, 34.365, 33.456,
32.603, 36.068, 38.951, 36.162,
35.960, 29.651, 33.950, 38.049,
34.000, 30.620, 30.284, 35.222],
'longitude': [-87.538, -91.177, -89.526, -88.811,
-85.484, -94.172, -92.328, -86.784,
-83.920, -82.324, -83.377, -84.500,
-81.034, -96.340, -97.740, -97.445]
}

df = pd.DataFrame(information)

Assigning Constants

The code will produce a distance map from one of many listed SEC faculties. We’ll assign the college’s identify (typed precisely because it seems within the dictionary) to a relentless named SCHOOL.

# Choose a faculty to plot the gap from. 
# Use the identical identify as within the information dict:
SCHOOL = 'Texas'

To regulate the “smoothness” of the contours, we’ll use a relentless named RESOLUTION. The bigger the quantity, the finer the underlying grid and thus the smoother the contours. Values round 500–1,000 produce good outcomes.

# Set the grid decision.
# Bigger = larger res and smoother contours:
RESOLUTION = 500

Getting the Faculty Location

Now to get the desired faculty’s map coordinates. On this case, the college would be the College of Texas in Austin, Texas.

# Get coordinates for SCHOOL:
school_index = df[df['school'] == SCHOOL].index[0]
school_coords = df.loc[school_index, ['latitude', 'longitude']].to_numpy()

The primary line identifies the DataFrame index of the college specified by the SCHOOL fixed. This index is then used to get the college’s coordinates. As a result of index returns a listing of indices the place the situation is true, we use [0] to get the primary (presumably solely) merchandise on this record.

Subsequent, we extract latitude and longitude values from the DataFrame and convert them right into a NumPy array with the to_numpy() methodology.

In the event you’re unfamiliar with NumPy arrays, take a look at this text:

Creating the Grid

Earlier than we make a contour map, we should construct an everyday grid and populate the grid nodes (intersections) with distance values. The next code creates the grid.

# Create grid of factors for interpolation:
x_min, x_max = df['longitude'].min(), df['longitude'].max()
y_min, y_max = df['latitude'].min(), df['latitude'].max()
xx, yy = np.meshgrid(np.linspace(x_min, x_max, RESOLUTION),
np.linspace(y_min, y_max, RESOLUTION))

Step one right here is to get the min and max values (x_min, x_max and y_min, y_max) of the longitude and latitude from the DataFrame.

Subsequent, we use NumPy’s meshgrid() methodology to create a grid of factors throughout the bounds outlined by the min and max latitudes and longitudes.

Right here’s how the grid seems to be for a decision of 100:

A visualization of the nodes (points) on a 2D mesh.
The grid nodes of a grid created with decision = 100 (by creator)

Every node will maintain a price that may be contoured.

Calculating Distances

The next code calculates concentric distances from the desired faculty.

# Calculate distances from SCHOOL to each level in grid:
distances = np.zeros(xx.form)
for i in vary(xx.form[0]):
for j in vary(xx.form[1]):
point_coords = (yy[i, j], xx[i, j])
distances[i, j] = great_circle(school_coords, point_coords).miles

The primary order of enterprise is to initialize a NumPy array referred to as distances. It has the identical form because thexx grid and is stuffed with zeroes. We’ll use it to retailer the calculated distances from SCHOOL.

Subsequent, we loop over the rows of the grid, then, in a nested loop, iterate over the columns of the grid. With every iteration we retrieve the coordinates of the purpose at place (i, j) within the grid, with yy and xx holding the grid coordinates.

The ultimate line calculates the great-circle distance (the gap between two factors on a sphere) from the college to the present level coordinates (point_coords). The last word result’s an array of distances with models in miles.

Creating the Map

Now that we’ve got x, y, and distance information, we are able to contour the gap values and make a show.

# Create the color-filled contour map:
fig, ax = plt.subplots(1, 1, figsize=(10, 8))
contour = ax.contourf(xx, yy, distances,
cmap='coolwarm',
alpha=0.9)
cbar = fig.colorbar(contour, ax=ax, shrink=0.7)
cbar.set_label(f'Distance from {SCHOOL} (miles)')
ax.scatter(df['longitude'], df['latitude'], s=2, shade='black')

We begin by organising a Matplotlib determine of measurement 10 x 8. In the event you’re not accustomed to the fig, ax terminology, take a look at this terrific article for a fast introduction:

To attract the color-filled contours we use Matplotlib’s contourf() methodology. It makes use of the xx, yy, and distancesvalues, the coolwarm colormap, and a slight quantity of transparency (alpha=0.9).

The default shade bar for the show is missing, for my part, so we customise it considerably. The fig.colorbar() methodology provides a shade bar to the plot to point the gap scale. The shrink argument retains the peak of the colour bar from being disproportionate to the plot.

Lastly, we use Matplotlib’s scatter() methodology so as to add the college places to the map, with a marker measurement of 2. Later, we’ll label these factors with the college names.

Including the State Boundaries

The map at present has solely the college places to make use of as landmarks. To make the map extra relatable, the next code provides state boundaries.

# Load state boundaries from US Census Bureau:
url = 'https://www2.census.gov/geo/tiger/GENZ2021/shp/cb_2021_us_state_20m.zip'
states = gpd.read_file(url)

# Filter states throughout the map limits:
states = states.cx[x_min:x_max, y_min:y_max]

# Plot the state boundaries:
states.boundary.plot(ax=ax, linewidth=1, edgecolor='black')

The third line makes use of geopandas’ cx indexer methodology for spatial slicing. It filters geometries in a GeoDataFrame primarily based on a bounding field outlined by the minimal and most x (longitude) and y (latitude) coordinates. Right here, we filter out all of the states exterior the bounding field.

Including Labels and a Title

The next code finishes the plot by tying up a number of unfastened ends, reminiscent of including the college names to their map markers, labeling the x and y axes, and setting an updateable title.

# Add labels for the colleges:
for i, faculty in enumerate(df['school']):
ax.annotate(
faculty,
(df['longitude'][i], df['latitude'][i]),
textcoords="offset factors",
xytext=(2, 1),
ha='left',
fontsize=8
)

ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_title(f'Distance from {SCHOOL} to Different SEC Faculties')
fig.savefig('distance_map.png', dpi=600)
plt.present()

To label the colleges, we use a for loop and enumeration to decide on the proper coordinates and names for every faculty and use Matplotlib’s annotate() methodology to submit them on the map. We use annotate() fairly than the textual content() methodology to entry the xytext argument, which lets us shift the label to the place we wish it.

Tags: LeeMapsOctProximityPythonVaughan

Related Posts

0 iczjhf5hnpqqpnx7.jpg
Artificial Intelligence

The Information Workforce’s Survival Information for the Subsequent Period of Information

March 9, 2026
Pramod tiwari wb1flr5fod8 unsplash scaled 1.jpg
Artificial Intelligence

LatentVLA: Latent Reasoning Fashions for Autonomous Driving

March 8, 2026
Mlm building simple semantic search engine hero 1024x572.png
Artificial Intelligence

Construct Semantic Search with LLM Embeddings

March 8, 2026
Image 186 1.jpg
Artificial Intelligence

The AI Bubble Has a Information Science Escape Hatch

March 7, 2026
Mlm 5 essential security patterns for robust agentic ai 2 1024x571.png
Artificial Intelligence

5 Important Safety Patterns for Sturdy Agentic AI

March 7, 2026
Pexels markus winkler 1430818 30901567 scaled 1.jpg
Artificial Intelligence

What Makes Quantum Machine Studying “Quantum”?

March 7, 2026
Next Post
Shutterstock Linus.jpg

90% of AI advertising and marketing is hype so 'I ignore it' • The Register

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

POPULAR NEWS

Chainlink Link And Cardano Ada Dominate The Crypto Coin Development Chart.jpg

Chainlink’s Run to $20 Beneficial properties Steam Amid LINK Taking the Helm because the High Creating DeFi Challenge ⋆ ZyCrypto

May 17, 2025
Gemini 2.0 Fash Vs Gpt 4o.webp.webp

Gemini 2.0 Flash vs GPT 4o: Which is Higher?

January 19, 2025
Image 100 1024x683.png

Easy methods to Use LLMs for Highly effective Computerized Evaluations

August 13, 2025
Blog.png

XMN is accessible for buying and selling!

October 10, 2025
0 3.png

College endowments be a part of crypto rush, boosting meme cash like Meme Index

February 10, 2025

EDITOR'S PICK

Mitchell Luo Z1c9juter5c Unsplash 1024x718 1.jpg

Benchmarking Tabular Reinforcement Studying Algorithms

May 6, 2025
1732954019 Ai Manufacturing Shutterstock 2377685503 Special.png

Embracing AI Units within the Office: Navigating the Moral Challenges

November 30, 2024
95081505 2b48 48c0 B9de Fca253f1dbe5 800x420.jpg

Bitcoin nears all-time excessive as Trump touts main progress with China

May 11, 2025
1oflsesn0x691cs1ujdpjua.jpeg

All You Have to Know In regards to the Non-Inferiority Speculation Take a look at | by Prateek Jain | Oct, 2024

October 19, 2024

About Us

Welcome to News AI World, your go-to source for the latest in artificial intelligence news and developments. Our mission is to deliver comprehensive and insightful coverage of the rapidly evolving AI landscape, keeping you informed about breakthroughs, trends, and the transformative impact of AI technologies across industries.

Categories

  • Artificial Intelligence
  • ChatGPT
  • Crypto Coins
  • Data Science
  • Machine Learning

Recent Posts

  • 10 GitHub Repositories to Grasp System Design
  • AMI is on the market for buying and selling!
  • The Information Workforce’s Survival Information for the Subsequent Period of Information
  • Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy

© 2024 Newsaiworld.com. All rights reserved.

No Result
View All Result
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us

© 2024 Newsaiworld.com. All rights reserved.

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?