You can download this code by clicking the button below.
This code is now available for download.
This function creates a map using the Basemap library and plots points on the map with given longitude and latitude values, each point having a specified color.
Technology Stack : Basemap, NumPy, Matplotlib
Code Type : Function
Code Difficulty : Intermediate
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
def plot_map_with_lons_lats(lons, lats, colors):
"""
This function creates a map using Basemap and plots points on the map with given longitude and latitude values.
"""
# Create a figure and an axis
fig, ax = plt.subplots()
# Create a Basemap instance
m = Basemap(projection='merc', llcrnrlat=-60, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180, lat_ts=20, resolution='c')
# Draw coastlines, countries, and meridians and parallels on the map
m.drawcoastlines()
m.drawcountries()
m.drawmeridians(np.arange(-180, 181, 30), labels=[0, 0, 0, 0])
m.drawparallels(np.arange(-90, 91, 30), labels=[0, 0, 0, 0])
# Scatter plot of longitude and latitude points with specified colors
x, y = m(lons, lats)
sc = m.scatter(x, y, c=colors, marker='o')
# Add a colorbar
cbar = plt.colorbar(sc)
cbar.set_label('Color Intensity')
# Show the plot
plt.show()
# Example usage:
lons = np.random.uniform(-180, 180, 100)
lats = np.random.uniform(-90, 90, 100)
colors = np.random.randint(0, 256, 100)
plot_map_with_lons_lats(lons, lats, colors)