top of page

Visualizing Capital Cities in India with Python: A Tutorial on Mapping Points from a CSV File

Writer's picture: Sonu SafalSonu Safal

Introduction:

Mapping data is a powerful way to visualize geographic information and uncover patterns that might not be evident in tabular formats. In this tutorial, we will explore how to create maps of capital cities in India using Python. By leveraging Python's geospatial libraries, we will load a CSV file containing the names, latitude, and longitude of Indian state capitals, convert the data into geospatial format, and visualize it. We will also enhance the map with a basemap for better context and create an interactive map where users can explore the cities interactively.

Prerequisites:

Before you begin, you need to have the following libraries installed:

  • Pandas: For data handling.

  • GeoPandas: For geospatial data manipulation.

  • Shapely: For creating geometries.

  • Matplotlib: for basic visualization.

  • Contextily: For adding basemaps to plots.

  • Folium: For creating interactive maps.


You can install these libraries using pip:

pip install
Setting Up the Project Folder Structure:

Create a project directory to organize your files. Include folders for data (e.g., CSV files), scripts, and outputs.

Introduction to the CSV File and Its Structure

The CSV file used in this tutorial contains the following columns:

  • City: Name of the capital city.

  • State: Name of the Indian state.

  • Latitude and Longitude: Geographic coordinates of the city.

Understanding the Data:

Overview of the Capital Cities Dataset

-The dataset includes information about 29 capital cities across India. Each row contains the name of the city, its state, and its geographic location.

Key Fields: Latitude, Longitude, and State Names

-Latitude and longitude are critical for plotting points on a map. The state names provide additional context for the data.

Checking and Cleaning the Dataset

-We will ensure the data is clean, free of missing values, and formatted correctly using Pandas.

Understanding the Data
Loading the Data into Python

-Reading the CSV File Using Pandas

-Load the CSV file and preview its contents.

Loading the Data into Python

Verifying the Data with Basic Pandas Operations

-Check for data types and ensure all columns are as expected.

Handling Missing or Incorrect Values

-Replace or drop any rows with invalid or missing values.

Converting Data into Geospatial Format

Introduction to GeoPandas and Geospatial Data

-GeoPandas extends Pandas to handle geospatial data, such as points, lines, and polygons.

Creating a GeoDataFrame from the CSV File

-Convert the latitude and longitude columns into a GeoDataFrame.

Converting Data into Geospatial Format

Setting the Coordinate Reference System (CRS)

-Define the CRS as WGS 84 (EPSG:4326), commonly used for geographic coordinates.

Setting the Coordinate Reference System (CRS)
Visualizing the Data with Matplotlib and GeoPandas

Plotting Points on a Simple Matplotlib Map

-Use GeoPandas’ built-in plotting functionality.

Visualizing the Data with Matplotlib and GeoPandas

Enhancing the Map with Labels and Titles

-Add labels for cities and titles for better readability.

Customizing Point Colors and Sizes

-Differentiate cities using unique colors or sizes.

Adding Basemaps with Contextily

Introduction to Contextily and Basemaps

-Contextily provides basemaps that can be added to GeoPandas plots.

Integrating a Basemap with the GeoDataFrame Plot

-Convert the GeoDataFrame CRS to a projection suitable for Contextily.

Adding Basemaps with Contextily
Creating an Interactive Map with Folium

Introduction to Folium for Interactive Mapping

-Folium allows for the creation of interactive web maps.

Generating the Base Map with Folium

-Create a Folium map centered on India.

Creating an Interactive Map with Folium
Enhancing the Interactive Map

Styling Markers with Custom Icons and Colors

-To make the map more visually appealing, customize the markers by changing their icons and colors. Using the Icon class in Folium, you can apply different colors and icons to represent specific data points or categories.

Enhancing the Interactive Map
  • Icon Color: Use colors like 'red', 'blue', 'green', etc., to differentiate markers.

  • Custom Icons: Icons such as cloud, home, or info-sign make the map intuitive and user-friendly.

Adding Layers for Improved User Experience

Provide users with the option to toggle between different basemaps, like satellite, terrain, or street views, to enhance their experience. Folium supports multiple basemaps using the TileLayer method.

Adding Layers for Improved User Experience
Basemap Layers

These basemap layers can be toggled interactively to provide different perspectives of the data.


Embedding a MiniMap Plugin for Context

-To give users a better spatial context, embed a MiniMap plugin on the map. This inset map shows an overview of the entire region while users navigate the main map.

-The MiniMap helps users identify the general location of the region they are viewing, improving navigation and usability.

Embedding a MiniMap Plugin for Context
Embedding a MiniMap Plugin for Context 1
Handling Projections and CRS Transformations

Understanding Projections in Geospatial Data

-Projections convert the Earth's spherical surface into a 2D map. Proper alignment between spatial data and basemaps is essential for accurate visualizations. The Web Mercator projection (EPSG:3857) is widely used for online mapping applications.

Transforming the CRS for Contextily Compatibility

-Ensure that your geospatial data matches the basemap's projection (EPSG:3857). Transform the GeoDataFrame’s CRS as shown below:

# Convert GeoDataFrame to EPSG:3857

gdf = gdf.to_crs(epsg=3857)


This ensures correct alignment between the data points and the basemap.

Exporting and Sharing the Map

Saving the Static Map as an Image

-Static maps are useful for presentations or reports. Use Matplotlib to save the map as an image:

Exporting and Sharing the Map
Exporting the Interactive Map as an HTML File

-Interactive maps can be saved as standalone HTML files, making them easy to share or embed:

# Save the Folium map as an HTML file

Exporting the Interactive Map as an HTML File

-This HTML file can be opened in any browser or embedded in websites to provide an interactive experience.

Technical Challenges and Solutions

Common Errors When Loading CSV Data

  • Missing Values: Use dropna() to remove rows with missing data or fillna() to replace them with default values.

  • Incorrect Delimiters: Specify the correct delimiter when loading the CSV file.

Common Errors When Loading CSV Data

Handling Coordinate Precision Issues

-Ensure precise plotting by rounding latitude and longitude values to a reasonable number of decimal places:

Handling Coordinate Precision Issues

Ensuring CRS Compatibility Between GeoPandas and Contextily

-Always reproject GeoDataFrames to EPSG:3857 before adding a Contextily basemap:

Ensuring CRS Compatibility Between GeoPandas and Contextily
Use Cases and Applications

Exploring Other Cities or Points of Interest

-Expand the dataset by adding more locations, such as airports, tourist attractions, or historical sites. You can plot these additional points similarly.

Using the Workflow for Similar Geospatial Projects

-Apply these techniques to create custom maps for various domains.


Conclusion:

This tutorial demonstrated how to visualize capital cities in India using Python. By combining GeoPandas, Contextily, and Folium, we created static and interactive maps. These techniques are not only useful for mapping cities but can be applied to numerous geospatial projects. Experiment with additional datasets and tools to further enhance your geospatial analysis skills.

Comments


bottom of page