Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon GeoPandas sample code


GeoPandas sample code


Here is a sample code snippet for GeoPandas:

python
import geopandas as gpd
import matplotlib.pyplot as plt

# Load the shapefile
gdf = gpd.read_file('path_to_your_shapefile.shp')

# Plot the data
gdf.plot(column='your_column_name', cmap='viridis')

# Add a title and labels
plt.title('Your Map Title')
plt.xlabel('Longitude')
plt.ylabel('Latitude')

# Show the plot
plt.show()

This code loads a shapefile using `gpd.read_file`, plots the data using `gdf.plot`, and adds a title and labels using `plt.title`, `plt.xlabel`, and `plt.ylabel`. Finally, it displays the plot using `plt.show`.

Explanation

1. Import Libraries: The code starts by importing the necessary libraries: `geopandas` for working with geospatial data and `matplotlib.pyplot` for plotting.

2. Load Shapefile: The `gpd.read_file` function is used to load the shapefile. Replace `'path_to_your_shapefile.shp'` with the actual path to your shapefile.

3. Plot Data: The `gdf.plot` function is used to plot the data. The `column` parameter specifies the column to use for the color palette. Replace `'your_column_name'` with the actual name of the column you want to use.

4. Add Title and Labels: The `plt.title`, `plt.xlabel`, and `plt.ylabel` functions are used to add a title and labels to the plot.

5. Show Plot: The `plt.show` function is used to display the plot.

Example Usage

Here is an example of how you might use this code:

python
import geopandas as gpd
import matplotlib.pyplot as plt

# Load the shapefile
gdf = gpd.read_file('path_to_your_shapefile.shp')

# Plot the data
gdf.plot(column='POPULATION', cmap='viridis')

# Add a title and labels
plt.title('Population Distribution')
plt.xlabel('Longitude')
plt.ylabel('Latitude')

# Show the plot
plt.show()

In this example, the code loads a shapefile, plots the population data using the `viridis` color palette, and adds a title and labels to the plot.

Citations:
[1] https://geopandas.org/en/stable/getting_started/introduction.html
[2] https://www.datacamp.com/tutorial/geopandas-tutorial-geospatial-analysis
[3] https://geopandas.org/en/stable/mapping.html
[4] https://github.com/jorisvandenbossche/geopandas-tutorial
[5] https://github.com/jorisvandenbossche/geopandas-tutorial/blob/main/01-introduction-geospatial-data.ipynb