SlideShare a Scribd company logo
Geospatial
Visualization
GeoPandas
2
What is Geopandas?
 GeoPandas is an open-source project to make
working with geospatial data in python easier.
 GeoPandas is one of the most satisfying Python
packages to use because it produces a tangible,
visible output that is directly linked to the real world.
 Here we will be exploring the method to create a geo
map and visualize data over it, using shapefiles(.shp)
and some other Python libraries.
3
The core data structure in GeoPandas
 GeoDataFrame, a subclass of pandas.
 DataFrame, that can store geometry columns and perform
spatial operations.
 The geopandas.GeoSeries, a subclass of pandas.Series,
handles the geometries.
 Therefore, your GeoDataFrame is a combination of
pandas.Series, with traditional data (numerical, boolean, text
etc.), and geopandas.GeoSeries, with geometries (points,
polygons etc.).
 You can have as many columns with geometries as you wish;
there’s no limit typical for desktop GIS software.
4
The core data structure in GeoPandas
5
The core data structure in GeoPandas
 Each GeoSeries can contain any geometry type (you can even
mix them within a single array) and has a GeoSeries.crs
attribute, which stores information about the projection (CRS
stands for Coordinate Reference System).
 Therefore, each GeoSeries in a GeoDataFrame can be in a
different projection, allowing you to have, for example,
multiple versions (different projections) of the same geometry.
 Only one GeoSeries in a GeoDataFrame is considered the
active geometry, which means that all geometric operations
applied to a GeoDataFrame operate on this active column.
6
world map projections.
 1. Mercator
 This projection was developed by Gerardus Mercator back in 1569
for navigational purposes.
 Its ability to represent lines of constant course from coast to coast
made it the perfect map for sailing the seas.
 Its popularity was so great that it became used as a geographic
teaching aid even though the projection grossly distorts countries
sizes.
 This is at its worst the closer you are to the poles. Greenland is 550%
too big, it should fit into Africa 14 times!
7
Vector Data: OpenGIS Simple Features / OCG Simple Feature Access
Used in spatial databases (Postgresql/PostGIS), GIS, …
WKT (Well known Text):
• Point, Multipoint
• LineString, MultiLineString
• Polygon, MultiPolygon
• GeometryCollection
• (TIN, Circle, Curve, Triangle, Surface, PolyhedralSurface,
…)
map projections.
8
Examples
9
Examples
10
world map projections.
 1. Mercator
 This projection was developed by
Gerardus Mercator back in 1569 for
navigational purposes.
 Its ability to represent lines of constant
course from coast to coast made it the
perfect map for sailing the seas.
 Its popularity was so great that it
became used as a geographic teaching
aid even though the projection grossly
distorts countries sizes.
 This is at its worst the closer you are to
the poles. Greenland is 550% too big, it
should fit into Africa 14 times!
11
Map projections.
 2. Robinson
 This map is known as a ‘compromise’, it shows neither the shape or land
mass of countries correct.
 Arthur Robinson developed it in 1963 using a more visual trial and error
development.
 Our Classic world map uses the Robinson projection and is a contemporary
tribute to the familiar schoolroom map and is perfect for map-lovers of all
ages..
12
map projections
 3. Dymaxion Map
 This projection was released by R Buckminster Fuller in 1954 after several
decades working on it.
 The world is projected onto the surface of a icosahedron, allowing it to be
unfolded and flattened in two dimensions.
 It is said to represent the Earth’s continents as “one island”.
13
map projections
 4. Gall-Peters
 This is a cylindrical world map projection, that regains accuracy in surface
area.
 It is named after James Gall and Arno Peters. Whilst Gall, first described
the projection in 1855 it was not until 1973 when Peters, began to heavily
market the projection as the ‘Peters World Map’ that it became popular.
14
map projections
5. Sinu-Mollweide
 Developed in 1953 by Allen K Philbrick, this projection fuses the
Sinusoidal projection , which was first used in the 16th Century, with Karl
Brandan Mollweide's map of 1805 and challenges our assumption of how
the flattened globe should look.
 Still an equal area projection that maintains fidelity of area, we like this
projection for its bold graphic view.
15
map projections
 6 Winkel Tripel
 A globe that is projected onto a flat surface giving it curved lines of latitude and
curved meridians.
 The projection, by Oswald Winkel in1921 was developed with the goal of minimizing
the three kinds of distortion: area, direction and distance.
 Thus it became the Tripel Projection (German for triple).
 The projection is neither equal-area nor conformal, its main feature is that all of the
parallels are curved except for the straight poles and equator.
 This gives a lovely spherical feeling to this two dimensional map.
16
Download Free Shapefile Maps
 https://www.igismap.com/download-free-shap
efile-maps/
 https://www.statsilk.com/maps/download-free-
shapefile-maps
 https://mapscaping.com/download-shapefiles-f
or-any-country/
17
GeoPandas packages:
 pandas
 shapely
 fiona
 pyproj
 packaging
 Further, matplotlib is an optional dependency,
required for plotting.
 GeoPandas using the conda package manager.
18
Reading and writing files
 Assuming you have a file containing both data and geometry
(e.g. GeoPackage, GeoJSON, Shapefile), you can read it using
geopandas.read_file(),
 which automatically detects the filetype and creates a
GeoDataFrame.
 This tutorial uses the "nybb" dataset, a map of New York
boroughs, which is available through the geodatasets package.
 Therefore, we use geodatasets.get_path() to download the
dataset and retrieve the path to the local copy.
19
Reading and writing files
 Assuming you have a file containing both data and geometry
(e.g. GeoPackage, GeoJSON, Shapefile), you can read it using
geopandas.read_file(),
 which automatically detects the filetype and creates a
GeoDataFrame.
 This tutorial uses the "nybb" dataset, a map of New York
boroughs, which is available through the geodatasets package.
 Therefore, we use geodatasets.get_path() to download the
dataset and retrieve the path to the local copy.
20
Writing files
 To write a GeoDataFrame back to file use
GeoDataFrame.to_file().
 The default file format is Shapefile, but you can
specify your own with the driver keyword.
21
Simple accessors and methods
 Now we have our GeoDataFrame and can start working with
its geometry.
 Since there was only one geometry column in the New York
Boroughs dataset, this column automatically becomes the
active geometry and spatial methods used on the
GeoDataFrame will be applied to the "geometry" column.
22
Simple accessors and methods
Measuring area
 To measure the area of each polygon (or MultiPolygon in this
specific case), access the GeoDataFrame.area attribute,
which returns a pandas.Series.
 Note that GeoDataFrame.area is just GeoSeries.area applied to
the active geometry column.
23
Simple accessors and methods
Getting polygon boundary and centroid
 To get the boundary of each polygon (LineString), access the
GeoDataFrame.boundary:
 Since we have saved boundary as a new column, we now have
two geometry columns in the same GeoDataFrame.
24
Simple accessors and methods
Getting polygon boundary and centroid
 To get the boundary of each polygon (LineString), access the
GeoDataFrame.boundary:
 Since we have saved boundary as a new column, we now have
two geometry columns in the same GeoDataFrame.
25
Simple accessors and methods
Measuring distance
 We can also measure how far each centroid is from the first centroid
location.
 Note that geopandas.GeoDataFrame is a subclass of pandas.DataFrame, so
we have all the pandas functionality available to use on the geospatial
dataset — we can even perform data manipulations with the attributes and
geometry information together.
26
Making maps
 GeoPandas can also plot maps, so we can check how the
geometries appear in space.
 To plot the active geometry, call GeoDataFrame.plot().
 To color code by another column, pass in that column as the
first argument.
 In the example below, we plot the active geometry column and
color code by the "area" column. We also want to show a
legend (legend=True).
27
Making maps
28
Making maps
 You can also explore your data interactively using
GeoDataFrame.explore(), which behaves in the same way
plot() does but returns an interactive map instead.
29
Making maps
 Switching the active geometry
(GeoDataFrame.set_geometry) to centroids, we can plot the
same data using point geometry..
30
Making maps
 And we can also layer both GeoSeries on top of each other.
We just need to use one plot as an axis for the other.
31
Step 1 : Installing GeoPandas and
Shapely
 need to install the GeoPandas and Shapely libraries in order to
plot a map, and these libraries do not come with the Anaconda
download.
 through the conda-forge channel with the following command
from your terminal
 or alternatively
 Shapely can be pip installed with the command
conda install -c conda-forge geopandas
pip install geopandas
pip install shapely
32
Importing the libraries
 Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import geopandas as gpd
import shapefile as shp
from shapely.geometry import Point
sns.set_style('whitegrid')
33
Load the data
 Use india-polygon.shp shape file to plot India map
 Load the data into a GeoDataFrame as shown below.
fp = r’ india-polygon.shp'
map_df = gpd.read_file(fp)
map_df_copy = gpd.read_file(fp)
map_df.head()
34
Plotting the Shapefiles
 One nice thing about
downloading a
GeoDataFrame, is that
we’ve already got enough
info to make a basic plot.
map_df.plot()
35
Adding better data insights into the
map
df = pd.read_csv('globallandslides.csv')
pd.set_option('display.max_columns', None)df = df[df.country_name=="India"]
df["Year"] = pd.to_datetime(df["event_date"]).dt.year
df = df[df.landslide_category=="landslide"]
state_df = ls_df["admin_division_name"].value_counts()
state_df = state_df.to_frame()
state_df.reset_index(level=0, inplace=True)
state_df.columns = ['State', 'Count']state_df.at[15,"Count"] = 69
state_df.at[0,"State"] = "Jammu and Kashmir" state_df.at[20,"State"] = "Delhi"
state_df.drop(7)
36
 data of the number of
landslides that have happened
in each state over the years
37
Merge the data
 We can now merge this above state data which contains
landslide information with map_df shapefile. We will use the
State column of both the data frames for merging purposes.
#Merging the data
merged = map_df.set_index('st_nm').join(state_df.set_index('State'))
merged['Count'] = merged['Count'].replace(np.nan, 0)
merged.head()
38
Plotting the data on the Shapefile
#Create figure and axes for Matplotlib and set the title
fig, ax = plt.subplots(1, figsize=(10, 10))
ax.axis('off')ax.set_title('Number of landslides in India state-wise',
fontdict={'fontsize': '20', 'fontweight' : '10'})# Plot the figure
merged.plot(column='Count',cmap='YlOrRd', linewidth=0.8, ax=ax,
edgecolor='0',legend=True,markersize=[39.739192, -104.990337],
legend_kwds={'label': "Number of landslides"})
39
Plotting the data on the Shapefile
40
plot the latitudes and longitudes
 We can also plot the latitudes and longitudes
of the occurred landslides on the map along
with the names of states as shown below.
 For this, you will need to find the shapefile
data for Indian states and their latitudes and
longitudes.
 have to plot data points on the map..
41

More Related Content

PDF
Web Mapping with Drupal
PPT
GIS_Whirlwind_Tour.ppt
PPT
GIS_Whirlwind_Tour.ppt
PPT
GIS_Whirlwind_Tour.ppt
PPT
GIS_Whirlwind_Tour.ppt
PDF
GIS and QGIS training notes
PDF
Smash & Geopaparazzi - State of the art 2021
Web Mapping with Drupal
GIS_Whirlwind_Tour.ppt
GIS_Whirlwind_Tour.ppt
GIS_Whirlwind_Tour.ppt
GIS_Whirlwind_Tour.ppt
GIS and QGIS training notes
Smash & Geopaparazzi - State of the art 2021

Similar to Geospatial Visualization for datascience (20)

PPTX
Geographic information system and remote sensing
PPT
remote sesing resolution for satelitte imag
PDF
Looking into the past - feature extraction from historic maps using Python, O...
PDF
Processing Landsat 8 Multi-Spectral Images with GRASS Tools & the potential o...
PDF
GIS_FDP_Final.pdf
PPT
GIS Data Types
PDF
An Overview of a Cartographic Package
PDF
Maperitive
PPT
Principles of GIS.Lecture201511_BGTD.ppt
PDF
Opensource gis development - part 2
PDF
Mapping in Drupal using OpenLayers
PDF
On 2D SLAM for Large Indoor Spaces: A Polygon-Based Solution
PPTX
MapInfo Professional 12.5 and Discover3D 2014 - A brief overview
PDF
Opensource gis development - part 4
PDF
Terra formation control or how to move mountains
ODP
The GRASS GIS software (with QGIS) - GIS Seminar
PDF
Geographical Information System (GIS) Georeferencing and Digitization, Bihar ...
PPTX
Introduction and Application of GIS
Geographic information system and remote sensing
remote sesing resolution for satelitte imag
Looking into the past - feature extraction from historic maps using Python, O...
Processing Landsat 8 Multi-Spectral Images with GRASS Tools & the potential o...
GIS_FDP_Final.pdf
GIS Data Types
An Overview of a Cartographic Package
Maperitive
Principles of GIS.Lecture201511_BGTD.ppt
Opensource gis development - part 2
Mapping in Drupal using OpenLayers
On 2D SLAM for Large Indoor Spaces: A Polygon-Based Solution
MapInfo Professional 12.5 and Discover3D 2014 - A brief overview
Opensource gis development - part 4
Terra formation control or how to move mountains
The GRASS GIS software (with QGIS) - GIS Seminar
Geographical Information System (GIS) Georeferencing and Digitization, Bihar ...
Introduction and Application of GIS
Ad

More from Sivam Chinna (10)

PPT
graph theory in applied mathematics with example
PPT
Use case diagram with example of illustration
PPT
SE Roger S. Pressman - Requirement Model.ppt
PPTX
Dimensionality Reduction and feature extraction.pptx
PPT
14078956.ppt
PPTX
pythonpandas-181223110521-1(1).pptx
PPTX
Pandas-(Ziad).pptx
PPTX
Clustering.pptx
PPTX
13. Anomaly.pptx
PPT
UNIT 5-ANN.ppt
graph theory in applied mathematics with example
Use case diagram with example of illustration
SE Roger S. Pressman - Requirement Model.ppt
Dimensionality Reduction and feature extraction.pptx
14078956.ppt
pythonpandas-181223110521-1(1).pptx
Pandas-(Ziad).pptx
Clustering.pptx
13. Anomaly.pptx
UNIT 5-ANN.ppt
Ad

Recently uploaded (20)

PDF
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PPTX
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
PPTX
Introduction-to-Cloud-ComputingFinal.pptx
PPT
ISS -ESG Data flows What is ESG and HowHow
PDF
Introduction to Data Science and Data Analysis
PPTX
IB Computer Science - Internal Assessment.pptx
PDF
Fluorescence-microscope_Botany_detailed content
PDF
Lecture1 pattern recognition............
PPT
Reliability_Chapter_ presentation 1221.5784
PPTX
Market Analysis -202507- Wind-Solar+Hybrid+Street+Lights+for+the+North+Amer...
PPTX
1_Introduction to advance data techniques.pptx
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
PPTX
DISORDERS OF THE LIVER, GALLBLADDER AND PANCREASE (1).pptx
PPTX
climate analysis of Dhaka ,Banglades.pptx
PPTX
STUDY DESIGN details- Lt Col Maksud (21).pptx
PPTX
Data_Analytics_and_PowerBI_Presentation.pptx
PPT
Quality review (1)_presentation of this 21
PPTX
oil_refinery_comprehensive_20250804084928 (1).pptx
PPTX
Acceptance and paychological effects of mandatory extra coach I classes.pptx
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
Introduction to Basics of Ethical Hacking and Penetration Testing -Unit No. 1...
Introduction-to-Cloud-ComputingFinal.pptx
ISS -ESG Data flows What is ESG and HowHow
Introduction to Data Science and Data Analysis
IB Computer Science - Internal Assessment.pptx
Fluorescence-microscope_Botany_detailed content
Lecture1 pattern recognition............
Reliability_Chapter_ presentation 1221.5784
Market Analysis -202507- Wind-Solar+Hybrid+Street+Lights+for+the+North+Amer...
1_Introduction to advance data techniques.pptx
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
DISORDERS OF THE LIVER, GALLBLADDER AND PANCREASE (1).pptx
climate analysis of Dhaka ,Banglades.pptx
STUDY DESIGN details- Lt Col Maksud (21).pptx
Data_Analytics_and_PowerBI_Presentation.pptx
Quality review (1)_presentation of this 21
oil_refinery_comprehensive_20250804084928 (1).pptx
Acceptance and paychological effects of mandatory extra coach I classes.pptx

Geospatial Visualization for datascience

  • 2. 2 What is Geopandas?  GeoPandas is an open-source project to make working with geospatial data in python easier.  GeoPandas is one of the most satisfying Python packages to use because it produces a tangible, visible output that is directly linked to the real world.  Here we will be exploring the method to create a geo map and visualize data over it, using shapefiles(.shp) and some other Python libraries.
  • 3. 3 The core data structure in GeoPandas  GeoDataFrame, a subclass of pandas.  DataFrame, that can store geometry columns and perform spatial operations.  The geopandas.GeoSeries, a subclass of pandas.Series, handles the geometries.  Therefore, your GeoDataFrame is a combination of pandas.Series, with traditional data (numerical, boolean, text etc.), and geopandas.GeoSeries, with geometries (points, polygons etc.).  You can have as many columns with geometries as you wish; there’s no limit typical for desktop GIS software.
  • 4. 4 The core data structure in GeoPandas
  • 5. 5 The core data structure in GeoPandas  Each GeoSeries can contain any geometry type (you can even mix them within a single array) and has a GeoSeries.crs attribute, which stores information about the projection (CRS stands for Coordinate Reference System).  Therefore, each GeoSeries in a GeoDataFrame can be in a different projection, allowing you to have, for example, multiple versions (different projections) of the same geometry.  Only one GeoSeries in a GeoDataFrame is considered the active geometry, which means that all geometric operations applied to a GeoDataFrame operate on this active column.
  • 6. 6 world map projections.  1. Mercator  This projection was developed by Gerardus Mercator back in 1569 for navigational purposes.  Its ability to represent lines of constant course from coast to coast made it the perfect map for sailing the seas.  Its popularity was so great that it became used as a geographic teaching aid even though the projection grossly distorts countries sizes.  This is at its worst the closer you are to the poles. Greenland is 550% too big, it should fit into Africa 14 times!
  • 7. 7 Vector Data: OpenGIS Simple Features / OCG Simple Feature Access Used in spatial databases (Postgresql/PostGIS), GIS, … WKT (Well known Text): • Point, Multipoint • LineString, MultiLineString • Polygon, MultiPolygon • GeometryCollection • (TIN, Circle, Curve, Triangle, Surface, PolyhedralSurface, …) map projections.
  • 10. 10 world map projections.  1. Mercator  This projection was developed by Gerardus Mercator back in 1569 for navigational purposes.  Its ability to represent lines of constant course from coast to coast made it the perfect map for sailing the seas.  Its popularity was so great that it became used as a geographic teaching aid even though the projection grossly distorts countries sizes.  This is at its worst the closer you are to the poles. Greenland is 550% too big, it should fit into Africa 14 times!
  • 11. 11 Map projections.  2. Robinson  This map is known as a ‘compromise’, it shows neither the shape or land mass of countries correct.  Arthur Robinson developed it in 1963 using a more visual trial and error development.  Our Classic world map uses the Robinson projection and is a contemporary tribute to the familiar schoolroom map and is perfect for map-lovers of all ages..
  • 12. 12 map projections  3. Dymaxion Map  This projection was released by R Buckminster Fuller in 1954 after several decades working on it.  The world is projected onto the surface of a icosahedron, allowing it to be unfolded and flattened in two dimensions.  It is said to represent the Earth’s continents as “one island”.
  • 13. 13 map projections  4. Gall-Peters  This is a cylindrical world map projection, that regains accuracy in surface area.  It is named after James Gall and Arno Peters. Whilst Gall, first described the projection in 1855 it was not until 1973 when Peters, began to heavily market the projection as the ‘Peters World Map’ that it became popular.
  • 14. 14 map projections 5. Sinu-Mollweide  Developed in 1953 by Allen K Philbrick, this projection fuses the Sinusoidal projection , which was first used in the 16th Century, with Karl Brandan Mollweide's map of 1805 and challenges our assumption of how the flattened globe should look.  Still an equal area projection that maintains fidelity of area, we like this projection for its bold graphic view.
  • 15. 15 map projections  6 Winkel Tripel  A globe that is projected onto a flat surface giving it curved lines of latitude and curved meridians.  The projection, by Oswald Winkel in1921 was developed with the goal of minimizing the three kinds of distortion: area, direction and distance.  Thus it became the Tripel Projection (German for triple).  The projection is neither equal-area nor conformal, its main feature is that all of the parallels are curved except for the straight poles and equator.  This gives a lovely spherical feeling to this two dimensional map.
  • 16. 16 Download Free Shapefile Maps  https://www.igismap.com/download-free-shap efile-maps/  https://www.statsilk.com/maps/download-free- shapefile-maps  https://mapscaping.com/download-shapefiles-f or-any-country/
  • 17. 17 GeoPandas packages:  pandas  shapely  fiona  pyproj  packaging  Further, matplotlib is an optional dependency, required for plotting.  GeoPandas using the conda package manager.
  • 18. 18 Reading and writing files  Assuming you have a file containing both data and geometry (e.g. GeoPackage, GeoJSON, Shapefile), you can read it using geopandas.read_file(),  which automatically detects the filetype and creates a GeoDataFrame.  This tutorial uses the "nybb" dataset, a map of New York boroughs, which is available through the geodatasets package.  Therefore, we use geodatasets.get_path() to download the dataset and retrieve the path to the local copy.
  • 19. 19 Reading and writing files  Assuming you have a file containing both data and geometry (e.g. GeoPackage, GeoJSON, Shapefile), you can read it using geopandas.read_file(),  which automatically detects the filetype and creates a GeoDataFrame.  This tutorial uses the "nybb" dataset, a map of New York boroughs, which is available through the geodatasets package.  Therefore, we use geodatasets.get_path() to download the dataset and retrieve the path to the local copy.
  • 20. 20 Writing files  To write a GeoDataFrame back to file use GeoDataFrame.to_file().  The default file format is Shapefile, but you can specify your own with the driver keyword.
  • 21. 21 Simple accessors and methods  Now we have our GeoDataFrame and can start working with its geometry.  Since there was only one geometry column in the New York Boroughs dataset, this column automatically becomes the active geometry and spatial methods used on the GeoDataFrame will be applied to the "geometry" column.
  • 22. 22 Simple accessors and methods Measuring area  To measure the area of each polygon (or MultiPolygon in this specific case), access the GeoDataFrame.area attribute, which returns a pandas.Series.  Note that GeoDataFrame.area is just GeoSeries.area applied to the active geometry column.
  • 23. 23 Simple accessors and methods Getting polygon boundary and centroid  To get the boundary of each polygon (LineString), access the GeoDataFrame.boundary:  Since we have saved boundary as a new column, we now have two geometry columns in the same GeoDataFrame.
  • 24. 24 Simple accessors and methods Getting polygon boundary and centroid  To get the boundary of each polygon (LineString), access the GeoDataFrame.boundary:  Since we have saved boundary as a new column, we now have two geometry columns in the same GeoDataFrame.
  • 25. 25 Simple accessors and methods Measuring distance  We can also measure how far each centroid is from the first centroid location.  Note that geopandas.GeoDataFrame is a subclass of pandas.DataFrame, so we have all the pandas functionality available to use on the geospatial dataset — we can even perform data manipulations with the attributes and geometry information together.
  • 26. 26 Making maps  GeoPandas can also plot maps, so we can check how the geometries appear in space.  To plot the active geometry, call GeoDataFrame.plot().  To color code by another column, pass in that column as the first argument.  In the example below, we plot the active geometry column and color code by the "area" column. We also want to show a legend (legend=True).
  • 28. 28 Making maps  You can also explore your data interactively using GeoDataFrame.explore(), which behaves in the same way plot() does but returns an interactive map instead.
  • 29. 29 Making maps  Switching the active geometry (GeoDataFrame.set_geometry) to centroids, we can plot the same data using point geometry..
  • 30. 30 Making maps  And we can also layer both GeoSeries on top of each other. We just need to use one plot as an axis for the other.
  • 31. 31 Step 1 : Installing GeoPandas and Shapely  need to install the GeoPandas and Shapely libraries in order to plot a map, and these libraries do not come with the Anaconda download.  through the conda-forge channel with the following command from your terminal  or alternatively  Shapely can be pip installed with the command conda install -c conda-forge geopandas pip install geopandas pip install shapely
  • 32. 32 Importing the libraries  Importing the libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import geopandas as gpd import shapefile as shp from shapely.geometry import Point sns.set_style('whitegrid')
  • 33. 33 Load the data  Use india-polygon.shp shape file to plot India map  Load the data into a GeoDataFrame as shown below. fp = r’ india-polygon.shp' map_df = gpd.read_file(fp) map_df_copy = gpd.read_file(fp) map_df.head()
  • 34. 34 Plotting the Shapefiles  One nice thing about downloading a GeoDataFrame, is that we’ve already got enough info to make a basic plot. map_df.plot()
  • 35. 35 Adding better data insights into the map df = pd.read_csv('globallandslides.csv') pd.set_option('display.max_columns', None)df = df[df.country_name=="India"] df["Year"] = pd.to_datetime(df["event_date"]).dt.year df = df[df.landslide_category=="landslide"] state_df = ls_df["admin_division_name"].value_counts() state_df = state_df.to_frame() state_df.reset_index(level=0, inplace=True) state_df.columns = ['State', 'Count']state_df.at[15,"Count"] = 69 state_df.at[0,"State"] = "Jammu and Kashmir" state_df.at[20,"State"] = "Delhi" state_df.drop(7)
  • 36. 36  data of the number of landslides that have happened in each state over the years
  • 37. 37 Merge the data  We can now merge this above state data which contains landslide information with map_df shapefile. We will use the State column of both the data frames for merging purposes. #Merging the data merged = map_df.set_index('st_nm').join(state_df.set_index('State')) merged['Count'] = merged['Count'].replace(np.nan, 0) merged.head()
  • 38. 38 Plotting the data on the Shapefile #Create figure and axes for Matplotlib and set the title fig, ax = plt.subplots(1, figsize=(10, 10)) ax.axis('off')ax.set_title('Number of landslides in India state-wise', fontdict={'fontsize': '20', 'fontweight' : '10'})# Plot the figure merged.plot(column='Count',cmap='YlOrRd', linewidth=0.8, ax=ax, edgecolor='0',legend=True,markersize=[39.739192, -104.990337], legend_kwds={'label': "Number of landslides"})
  • 39. 39 Plotting the data on the Shapefile
  • 40. 40 plot the latitudes and longitudes  We can also plot the latitudes and longitudes of the occurred landslides on the map along with the names of states as shown below.  For this, you will need to find the shapefile data for Indian states and their latitudes and longitudes.  have to plot data points on the map..
  • 41. 41