<jupyter_start><jupyter_text>Map projections**Coordinate reference systems (CRS)** are important because the geometric shapes in a GeoDataFrame are simply a collection of coordinates in an arbitrary space. A CRS tells Python how those coordinates are related to places on the Earth. **A map projection** (or a projected coordinate system) is a systematic transformation of the latitudes and longitudes into a plain surface where units are quite commonly represented as meters (instead of decimal degrees). This transformation is used to **represent the three dimensional earth on a flat, two dimensional map**.As the CRS in different spatial datasets differ fairly often (i.e. one might have coordinates defined in decimal degrees while the other one has them in meters), it is a common procedure to **reproject** (or redefine) different layers into a common CRS. It is important that the layers are in the same coordinate reference system when analyzing the spatial relationships between the layers, for example, when making a Point in Polygon -query, or other type of overlay analysis.Choosing an appropriate projection for your map is not always straightforward because it depends on what you actually want to represent with your map, and what is the spatial scale of your data. In fact, there does not exist a "perfect projection" since each one of them has some strengths and weaknesses, and you should choose such projection that fits best for your needs. In fact, the projection you choose might even tell something about you 😉:    ![](img/Map-projections.png)*Source: XKCD, See a full comic about ["What your favorite map projection tells about you"](https://xkcd.com/977/)*.For those of you who want a bit more analytical approach for choosing the projection, you can get a good overview from [georeference.org](http://www.georeference.org/doc/guide_to_selecting_map_projections.htm), or from this blog post introducing [the strengths and weaknesses of a few commonly used projections](http://usersguidetotheuniverse.com/index.php/2011/03/03/whats-the-best-map-projection/).  Coordinate reference system (CRS) in GeopandasLuckily, defining and changing projections is easy in Geopandas. In this tutorial we will see **how to retrieve thecoordinate reference system information from the data, and how to change the crs**. We will re-project a data file fromWGS84 (lat, lon coordinates) into a Lambert Azimuthal Equal Area projection which is the [recommended projection forEurope](http://mapref.org/LinkedDocuments/MapProjectionsForEurope-EUR-20120.pdf) by European Commission.For this tutorial we will be using a Shapefile called `Europe_borders.shp` representing the country borders in Europe, that you already should have [downloaded during the previous tutorial](geopandas-basics.ipynb) into `L2_data` folder. In Shapefiles, information about the coordinate reference system i stored in the `.prj` -file (if this file is missing, you might be in trouble!). When reading the data into `GeoDataFrame` with Geopandas crs information is automatically stored into the `.crs` attribute of the GeoDataFrame.- Let's start by reading the data from the `Europe_borders.shp` file and checking the `crs`:<jupyter_code># Import necessary packages
import geopandas as gpd

# Read the file
fp = "L2_data/Europe_borders.shp"
data = gpd.read_file(fp)
# Check the coordinate reference system
data.crs<jupyter_output><empty_output><jupyter_text>As we can see, here, the `crs` is a Python dictionary with a key `init` that has a value `epsg:4326`. This is a very typical way how CRS is stored in GeoDataFrames. There are, however, other more informative formats for representing the coordinate reference system, which we will learn in a bit. The EPSG number (named after the *European Petroleum Survey Group*) is a code that tells about the coordinate system of the dataset. "[EPSG Geodetic Parameter Dataset](http://www.epsg.org/) is a collection of definitions of coordinate reference systems and coordinate transformations which may be global, regional, national or local in application".The EPSG code of our geodataframe is`4326`, which refers to the WGS84 coordinate system (we can also figure this out by looking at the coordinates values which are longitude and latitudes decimal degrees).You can find a lot of information and lists of available coordinate reference systems from:  - [www.spatialreference.org](http://spatialreference.org/)  - [www.proj4.org](https://proj4.org/operations/projections/)  - [www.mapref.org](http://mapref.org/CollectionofCRSinEurope.html) - Let's continue by checking the values in our `geometry` -column to verify that the CRS of our GeoDataFrame seems correct:<jupyter_code>data['geometry'].head()<jupyter_output><empty_output><jupyter_text>As we can see, the coordinate values of the Polygons indeed look like latitude and longitude values, so everything seems to be in order.WGS84 projection is not really a good one for representing European borders (areas get distorted), so let's convert those geometries into Lambert Azimuthal Equal Area projection ([EPSG: 3035](http://spatialreference.org/ref/epsg/etrs89-etrs-laea/)) which is the recommended projection by European Comission.Changing the projection is simple to [do in Geopandas](http://geopandas.org/projections.htmlre-projecting) with `.to_crs()` -function which is a built-in function of the GeoDataFrame. The function has two alternative parameters 1) `crs` and 2) `epgs` that can be used to make the coordinate transformation and re-project the data into the CRS that you want to use. - Let's re-project our data into `EPSG 3035` using `epsg` -parameter:<jupyter_code># Let's make a backup copy of our data
data_wgs84 = data.copy()

# Reproject the data
data = data.to_crs(epsg=3035)
# Check the new geometry values
print(data['geometry'].head())<jupyter_output>0    POLYGON ((4221214.558 3496203.404, 4220681.651...
1    POLYGON ((4224860.478 2732279.320, 4224932.819...
2    POLYGON ((4104652.176 3390034.953, 4104460.401...
3    POLYGON ((4113025.664 3391895.756, 4112879.943...
4    POLYGON ((4115871.228 3395282.099, 4114921.348...
Name: geometry, dtype: geometry<jupyter_text>And here we go, the coordinate values in the geometries have changed! Now we have successfully changed the projection of our layer into a new one, i.e. to `ETRS-LAEA` projection. To really understand what is going on, it is good to explore our data visually. Hence, let's compare the datasets by makingmaps out of them.<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt

# Make subplots that are next to each other
fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, figsize=(12, 8))

# Plot the data in WGS84 CRS
data_wgs84.plot(ax=ax1, facecolor='gray');

# Add title
ax1.set_title("WGS84");

# Plot the one with ETRS-LAEA projection
data.plot(ax=ax2, facecolor='blue');

# Add title
ax2.set_title("ETRS Lambert Azimuthal Equal Area projection");

# Remove empty white space around the plot
plt.tight_layout()<jupyter_output><empty_output><jupyter_text>Indeed, the maps look quite different, and the re-projected one looks much better in Europe as the areas especially in the north are more realistic and not so stretched as in WGS84.- Finally, let's save our projected layer into a Shapefile so that we can use it later.<jupyter_code># Ouput filepath
outfp = "L2_data/Europe_borders_epsg3035.shp"
    
# Save to disk
#data.to_file(outfp)<jupyter_output><empty_output><jupyter_text>Dealing with different CRS formats There are various ways to present Coordinate Reference System information, such as [PROJ strings](https://proj.org/usage/quickstart.html), `EPSG codes`, `Well-Known-Text (WKT)`, `JSON`. It is likely that you will encounter some of these when working with spatial data obtained from different sources. Being able to convert the CRS information from one format to another is needed every now and then, hence, it is useful to know a few tricks how to do this.Luckily, dealing with CRS information is easy in Python using a library called [pyproj](https://pyproj4.github.io/pyproj/stable/). In fact, `pyproj` is a Python wrapper around a software called [PROJ](https://proj.org/) (maintained by [OSGeo](https://www.osgeo.org/) community), which is widely used tool for conducting coordinate transformations in various GIS softwares. `Pyproj` is also used under the hood in Geopandas, and it handles all the CRS definitions and coordinate transformations (reprojecting from CRS to another as we did earlier).Next, let's see how it is possible to easily extract useful information from CRS, and transform CRS information from format to another. `pyproj` -library has a [class](https://docs.python.org/3/tutorial/classes.html) called [CRS](https://pyproj4.github.io/pyproj/dev/api/crs.html) that provides many useful functionalities for dealing with CRS information.<jupyter_code># Let's see the current CRS of our data
print(data.crs)<jupyter_output>{'init': 'epsg:3035', 'no_defs': True}<jupyter_text>The `data.crs` returns the coordinate reference system as a dictionary of PROJ parameters. From here we can easily see that the EPSG code of the data is `3035`. However, let's see how the same information looks like in other formats such as `WKT` or `Proj4` text. For this we need to use the `CRS` class.   **Updating pyproj**    If you are using your own computer and are having trouble importing the CRS class from the pyproj module, try updating pyproj:```conda update pyproj -c conda-forge```The following examples have been tested to work with `pyproj` version `2.4.0` and `geopandas` version `0.6.1`. You can check package versions by running the `conda list` -command.<jupyter_code>### Import CRS class from pyproj
from pyproj import CRS

# Initialize the CRS class for epsg code 3035:
crs_object = CRS.from_epsg(3035)
crs_object<jupyter_output><empty_output><jupyter_text>As we can see, the `CRS` object contains a lot more information than the original crs dictionary. The data contains some useful information such as the `Name` of the CRS (ETRS89/LAEA Europe), the `area` where the CRS is in use (*Europe* with bounds *(-16.1, 32.88, 40.18, 84.17)*), and the `Datum` (European Terrestrial Reference System 1989). We can also easily parse this information individually as follows:<jupyter_code># Name
print("Name:", crs_object.name)

# Coordinate system
print("Coordinate system:", crs_object.coordinate_system)

# Bounds of the area where CRS is used
print("Bounds:", crs_object.area_of_use.bounds)<jupyter_output>Name: ETRS89-extended / LAEA Europe
Coordinate system: cartesian
Bounds: (-35.58, 24.6, 44.83, 84.17)<jupyter_text>You can easily explore all the possible information that can be extracted from the CRS by typing `crs_info.` and pressing Tabulator. Let's see how we can convert the crs information from one format to another. Quite often it is useful to know the EPSG code of the CRS. Next, we will conduct a few transformations to demonstrate the capabilities of the `CRS` class.<jupyter_code># Retrive CRS information in WKT format
crs_wkt = crs_object.to_wkt()
print(crs_wkt)<jupyter_output>PROJCRS["ETRS89-extended / LAEA Europe",BASEGEOGCRS["ETRS89",DATUM["European Terrestrial Reference System 1989",ELLIPSOID["GRS 1980",6378137,298.257222101,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4258]],CONVERSION["Europe Equal Area 2001",METHOD["Lambert Azimuthal Equal Area",ID["EPSG",9820]],PARAMETER["Latitude of natural origin",52,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8801]],PARAMETER["Longitude of natural origin",10,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8802]],PARAMETER["False easting",4321000,LENGTHUNIT["metre",1],ID["EPSG",8806]],PARAMETER["False northing",3210000,LENGTHUNIT["metre",1],ID["EPSG",8807]]],CS[Cartesian,2],AXIS["northing (Y)",north,ORDER[1],LENGTHUNIT["metre",1]],AXIS["easting (X)",east,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["unknown"],AREA["Europe - LCC & LAEA"],BBOX[24.6,-35.58,84.17,44.83]],ID["EPSG",3035]]<jupyter_text>As we can see, the `WKT` format contains a *lot* of information. Typically, e.g. the `.prj` file of a Shapefile contains the information in this format. Let's see how it is possible to extract `EPSG` code from this. For doing it, we need to re-initialize the CRS object, this time from the `WKT` text presentation.<jupyter_code># Retrieve EPSG code from WKT text
epsg = CRS(crs_wkt).to_epsg()
print(epsg)<jupyter_output>3035<jupyter_text>**Not able to recognize epsg?**    Sometimes `to_epsg()` isn't able to recognize the EPSG code from the WKT representation. This can happen if the WKT information is missing some details. Luckily, we can easily adjust the minimum level of confidence for matching the CRS info and the EPSG code. We can do this by adjusting a parameter `min_confidence` when calling the function. By default, the confidence level is 70 %, but it is also possible to set a lower confidence threshold.     The coordinate information of our input shapefile is incomplete, and does not yield an epsg value with default setting: However, CRS is able to determine the EPSG value with a lower confidence treshold:     ``` Let's try to extract the EPSG code from the crs of our original data:CRS(data.crs).to_epsg()>>> None     Let's try it again with a lower confidence requirement (25 %)CRS(data.crs).to_epsg(min_confidence=25)>>> 3035```However, be cautious when using this, as guessing the EPSG from "exotic" coordinate reference systems might also provide false results.  Let's now save our data to disk using the `WKT` format as the crs of our GeoDataFrame. WKT is a [preferred output format](https://proj.org/faq.htmlwhat-is-the-best-format-for-describing-coordinate-reference-systems) for crs information:<jupyter_code># Re-define the CRS of the input GeoDataFrame 
data.crs = CRS.from_epsg(3035).to_wkt()
print(data.crs)
# Ouput filepath
outfp = "L2_data/Europe_borders_epsg3035.shp"
    
# Save to disk
#data.to_file(outfp)<jupyter_output><empty_output><jupyter_text>That's it. **HINT**: A module called [PyCRS](https://github.com/karimbahgat/PyCRS) can also be useful library as it contains information and supports many different coordinate reference definitions, such as OGC WKT (v1), ESRI WKT, Proj4, and any EPSG, ESRI, or SR-ORG code available from spatialreference.org.  Overview of different crs formatsSummary of different ways of representing crs information using pyproj CRS. Here, we use the crs of the original European borders layer as a starting point:<jupyter_code># PROJ dictionary:
crs_dict = data_wgs84.crs

# pyproj CRS object:
crs_object = CRS(data_wgs84.crs)

# EPSG code (here, the input crs information is a bit vague so we need to lower the confidence threshold)
crs_epsg = CRS(data_wgs84.crs).to_epsg(min_confidence=25)

# PROJ string
crs_proj4 = CRS(data_wgs84.crs).to_proj4()

# Well-Known Text (WKT)
crs_wkt = CRS(data_wgs84.crs).to_wkt()
print("PROJ dictionary:\n", crs_dict)
print("\nCRS object:\n", crs_object)
print("\nEPSG code: \n", crs_epsg)
print("\nPROJ string: \n", crs_proj4)
print("\nWell-Known Text (WKT):\n",crs_wkt)<jupyter_output>PROJ dictionary:
 {'init': 'epsg:4326'}

CRS object:
 +init=epsg:4326 +type=crs

EPSG code: 
 4326

PROJ string: 
 +proj=longlat +datum=WGS84 +no_defs +type=crs

Well-Known Text (WKT):
 GEOGCRS["WGS 84",DATUM["World Geodetic System 1984",ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]],ID["EPSG",6326]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8901]],CS[ellipsoidal,2],AXIS["longitude",east,ORDER[1],ANGLEUNIT["degree",0.0174532925199433,ID["EPSG",9122]]],AXIS["latitude",north,ORDER[2],ANGLEUNIT["degree",0.0174532925199433,ID["EPSG",9122]]],USAGE[SCOPE["unknown"],AREA["World"],BBOX[-90,-180,90,180]]]<jupyter_text>Global map projectionsFinally, let's play around with global map projections :) `L2_data` folder conaints a layer `ne_110m_admin_0_countries.shp` that represents the country borders of the world. The data was fownloaded from https://www.naturalearthdata.com/. **TASK**    Read in a global dataset and plot three maps with different projections! See hints and projection definitions from:    - http://geopandas.org/projections.html- https://pyproj4.github.io/pyproj/dev/api/crs.html- https://spatialreference.org/    When plotting the maps, think about the advantages and disadvantages of different world map projections.    Example solution:<jupyter_code># Read in data
fp = "L2_data/ne_110m_admin_0_countries.shp" 
admin = gpd.read_file(fp)
# Check input crs
admin.crs
# Set fig size
plt.rcParams['figure.figsize'] = [12, 6]
#Plot in original crs
admin.plot()
plt.title("WGS84")
# Define projection as web mercator, 3785
web_mercator = CRS.from_epsg(3785)

# Re-project and plot
admin.to_crs(web_mercator).plot()

# Remove x and y axis
plt.axis('off')
plt.title("Web mercator")
# Define projection Eckert IV from https://spatialreference.org/ref/esri/54012/
eckert_IV = CRS.from_proj4("+proj=eck4 +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")

# Re-project and plot
admin.to_crs(eckert_IV).plot()

# Remove x and y axis
plt.axis('off')
plt.title("Eckert IV")
# Define an orthographic projection, centered in Finland! from: http://www.statsmapsnpix.com/2019/09/globe-projections-and-insets-in-qgis.html
ortho = CRS.from_proj4("+proj=ortho +lat_0=60.00 +lon_0=23.0000 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs")

# Re-project and plot
admin.to_crs(ortho).plot()

# Remove x and y axis
plt.axis('off')
plt.title("Orthographic")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09660930311807804, 'fraction_numerical': 0.03930255012211052, 'mean_word_length': 5.599700149925037, 'pattern_counts': {'":': 0, '<': 47, '<?xml version=': 0, '>': 53, 'https://': 14, 'lorem ipsum': 0, 'www.': 8, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '13', 'dir': 'jupyter-structured-clean-dedup', 'id': '367037', 'license': 'MIT', 'n_tokens_mistral': 5949, 'n_tokens_neox': 5342, 'n_words': 2055, 'path': 'source/notebooks/L2/projections.ipynb', 'repo_name': 'GIS-enthusiast/site', 'size': '17607'}