In this tutorial, we will learn how to plot geographical coordinates (latitude and longitude) on a map in Python. Mapping data is an integral part of data visualization and analysis, especially when dealing with geospatial data. We will use geospatial libraries in Python to achieve our goal.
Step One: Installation
Before we begin, we need to ensure we have the required libraries: Pandas, Matplotlib, and Geopandas. You can install them using pip:
1 |
pip install pandas matplotlib geopandas |
Step Two: Importing Libraries
Once installed, we import these libraries into our Python script.
1 2 3 4 |
import pandas as pd import geopandas as gpd from shapely.geometry import Point import matplotlib.pyplot as plt |
Step Three: Creating a Dataframe
We assume that our raw data includes columns for latitude and longitude. Here’s an example dataframe:
{'City': ['New York', 'Los Angeles', 'Chicago'], 'Latitude': [40.7128, 38.9072, 41.8781], 'Longitude': [-74.0060, -77.0369, -87.6298]}
Step Four: Transforming the Data
Now, we convert our dataframe into a GeoDataFrame, which is a data structure in Geopandas. This lets us handle geometrical data types (like points, lines, and polygons). We convert the latitudes and longitudes into Points:
1 2 |
geometry = [Point(xy) for xy in zip(df['Longitude'], df['Latitude'])] gdf = gpd.GeoDataFrame(df, geometry=geometry) |
Step Five: Plotting the Data
We need a World map on which we can plot our points. Geopandas includes a built-in dataset, which can be loaded as a GeoDataFrame:
1 |
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) |
Now, we plot our World map and points:
1 2 |
world.plot() gdf.plot(marker='o', color='red', markersize=5, ax=plt.gca()) |
The above code adds our coordinates to the map as red circles.
Step Six: Finishing the Plot
To complete our map, we add a title, and display it:
1 2 |
plt.title('Cities on a World Map') plt.show() |
Complete Code
Here is the full script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import pandas as pd import geopandas as gpd from shapely.geometry import Point import matplotlib.pyplot as plt df = pd.DataFrame({ 'City': ['New York', 'Los Angeles', 'Chicago'], 'Latitude': [40.7128, 38.9072, 41.8781], 'Longitude': [-74.0060, -77.0369, -87.6298], }) geometry = [Point(xy) for xy in zip(df['Longitude'], df['Latitude'])] gdf = gpd.GeoDataFrame(df, geometry=geometry) world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) world.plot() gdf.plot(marker='o', color='red', markersize=5, ax=plt.gca()) plt.title('Cities on a World Map') plt.show() |
Output
Conclusion
You’ve learned how to plot latitude and longitude coordinates onto a map in Python using pandas, geopandas, and matplotlib. This will allow you to work with and visualize geospatial data effectively in your future projects.