Creating Choropleth Map Using GeoPandas — Irish Wind Energy Dataset | by Saeed Misaghian | Towards Data Science

In my previous article [1] I discussed Irish wind energy penetration within the electricity network . In that article, I reported figures representing the change in the number of wind turbines in each country over the past few years. Below, I will go through the steps involved in creating your own choropleth map for visualizing any data of your choice!
For illustration purposes, the code below is for generating the figure I reported in my previous article. However, these steps apply to any data!
Following the steps detailed below, we will generate the choropleth map shown below. This map color codes the different Irish counties based on the wind turbine installed capacity. The number of wind turbines installed in each county is illustrated by dots where each dot is one wind turbine.
All you need to create this map is some hands on Python (Pandas, Matplotlib) and I will help you with GeoPandas.
We will breakdown generating the choropleth map into the followng steps:
Data curation:
Data curation:
Because I’m based in Dublin and working on renewable energies; I will be plotting the wind turbine installation in terms of number of turbines and capacity, you can just follow the process for your data to create your own.
The energy data was curated from EirGrid website [2]. The data is in PDF format. I converted it into CSV file, did a little bit of preprocessing to it and uploaded it to my GitHub. The curated data is perfect for our illustration purposes.
We also need to have access to the map in question. I used the map of the Republic of Ireland, which I downloaded from the following website which I also uploaded into my GitHub.
2. Let’s start coding:
I know it might be your first time working with GeoPands, so at first you need to install it. This can be done by running the following line of code:
pip install geopandas
If you got an error, don’t panic, there are other ways to install it. Have a look at this.
To load the CSV file in question, execute the following lines of code:
import pandas as pdpath = 'Give it the data path'  df = pd.read_csv(path+'Tdata.csv')df.head() # to see how data look likes
A shown, we have the the installed capacity and number of turbines for each county in Ireland in the loaded dataset. Now, we need to load the map in question, which is in this case the map of Ireland.
import geopandas as gpdROI_map= gpd.read_file(path+'IRL_adm1.shp')  #reading the map ROI_map.NAME_1 #you can see names of counties here
Now, we have a Panadas dataframe representing our data (df) and a GeoPandas dataframe representing Ireland map (ROI_map). What we need to do is to merge these two data sets based on the county names:
ROI_map=ROI_map.set_index('NAME_1')df=df.set_index('County')df2= ROI_map.join(df)# we need to replace NaN rows with 0 since there are some counties #without any wind turbines df2['Installed Capacity (MW)']=df2['Installed Capacity (MW)'].fillna(value=0)df2['No of Turbines']=df2['No of Turbines'].fillna(value=0)df2['name1'] = df2.indexdf2.head() # it is the new data frame that we created merging map and wind data sets
2. Ready to plot?
To plot the data in question, we use the MatPlotlib library in Python. I color coded each county based on the installed capacity. I chose green because I’m talking about green energies (cmap=’YlGn’). One point I like to touch on here is that since we are coloring the map based on the installed capacity, we need a color bar showing how the range of installed capacity is changing with color, so you need to define the minimum (vmin) and maximum (vmax) of installed capacity for the color bar too. WAIT! We are talking about island of Ireland, so I like the face color of my plot to be light blue (facecolor=’lightsteelblue’), you can remove it if you want it to be white.
import matplotlib.pyplot as pltvmin, vmax = 0, 500 #Range of variable you use as map color (here #range of Installed Capacity (MW)fig, ax = plt.subplots(figsize=(6,8),facecolor='lightsteelblue')fig=df2.plot(column='Installed Capacity (MW)', cmap='YlGn', linewidth=0.8, ax=ax, edgecolor='#140656',facecolor='lightslategray',vmin=vmin, vmax=vmax,legend=True, norm=plt.Normalize(vmin=vmin, vmax=vmax))ax.axis('off')
Add a legend to the color bar:
ax.annotate('Installed Capacity (MW)',xy=(0.9, .65),rotation=270, xycoords='figure fraction', horizontalalignment='left', verticalalignment='top', fontsize=12, color='black')
Here is your plot so far:
3. Can we add county names?
YES! You can assign anything you want by specifying the longitude and latitude. You might be interested in adding county names to your plot, so let’s take the longitude and latitude of each county and ask Python to add names on this basis.
#Getting the lan and lat here from geometry datadf2['coords']=df2['geometry'].apply(lambda x: x.representative_point().coords[:])df2['coords']=[coords[0] for coords in df2['coords']]#Add names of county herefor idx, row in df2.iterrows():    plt.annotate(s=row['name1'], xy=row['coords'],                 horizontalalignment='center', color='black',fontsize=10, fontweight='light')
There are some overlapping of names, but you can avoid it by adjusting the layout or changing the size of figure.
4. What about number of wind turbines?
Of course! It is quite similar to part 3, yet there is a small difference, instead of adding names, add number of wind turbines! BUT, be careful, I liked to distribute the circles across the county to clearly show the cumulative of wind turbines, since otherwise, all circles would overlap at the same spot and we wouldn’t tell how many are there!, so I just produced some random numbers for each county and each turbine; hence; you would have equal number of circles and wind turbines in each county.
from random import gauss # Add turbine numbers herefor idx, row in df2.iterrows():    if row['No of Turbines']!=0:        s=row['No of Turbines']        ss=int(s)        for i in list(range(ss)):            z=row['No of Turbines']/1000+gauss(0, 0.1)            DFF=plt.scatter(x=z+row['coords'][0],y=gauss(0, 0.03)+row['coords'][1],c='#ec1313',alpha=0.5)
Finally we have:
5. Stop! We always need legend for our data!
Add legend to the map by the following code:
#Add legend to red circles i.e. wind turbinesplt.legend([DFF, DFF], ["Wind turbines"],loc='upper left')
Here we go:
6. Can I save my map?
You can save your map by the following code:
import os path2='your path here!'filepath = os.path.join(path2,'mymap.jpg')chart = fig.get_figure()chart.savefig(filepath, dpi=300)
6. BYE!
I Hope you enjoyed this article and I wish it could help you with your study or work.
You can access the code and data on my GitHub.
It is worth to note that I have been inspired by these two articles [3,4] on Towards Data Science.
I want to acknowledge UCD energy institute and ESIPP group for supporting me. Plus, I recommend you have a look at my colleagues’ interesting works in this institute.
[1]: Green like Ireland: Choropleth map of Irish wind energy, Towards Data science; Feb. 23, 2021 https://towardsdatascience.com/green-like-ireland-choropleth-map-of-irish-wind-energy-26603106fe3e?source=social.tw
[2]: TSO Connected Renewables — Annual Installed Capacities, EirGrid, Feb. 2021. http://www.eirgridgroup.com/site-files/library/EirGrid/TSO-Connected-Renewable-Generation.pdf
[3]: A Complete Guide to creating Choropleth Maps in Python, Towards Data science; Oct. 4, 2020 https://towardsdatascience.com/a-complete-guide-to-creating-choropleth-maps-in-python-728ee2949db4
[4]: Let’s make a map! Using Geopandas, Pandas and Matplotlib to make a Choropleth map; Jun 25, 2018. https://towardsdatascience.com/lets-make-a-map-using-geopandas-pandas-and-matplotlib-to-make-a-chloropleth-map-dddc31c1983d