Home Artificial Intelligence Visualizing trade flow in Python maps — Part I: Bi-directional trade flow maps Finding Coordinates of Arrows Data Code description Conclusion

Visualizing trade flow in Python maps — Part I: Bi-directional trade flow maps Finding Coordinates of Arrows Data Code description Conclusion

0
Visualizing trade flow in Python maps — Part I: Bi-directional trade flow maps
Finding Coordinates of Arrows
Data
Code description
Conclusion

Within the trade flow maps, I aimed to represent two-way trade relationships between countries. For instance, the export from Nepal to India could be represented by the primary arrow (A1-A2) and the import by Nepal from India could be represented by a second arrow (A3-A4). In this fashion, each country pair relationship would require 4 coordinate points to define the beginning and end points of arrows to represent exports and imports respectively.

While it’s also possible to assume a coordinate that may be detected robotically (for instance, the centroid of a rustic geometry), I intended to mark the points in a map and get their coordinates individually. For this purpose, it is feasible to create a project in an application reminiscent of Google Earth, export a KML file, and extract the coordinates with a converter (for instance, the GIS data converter in the web site of MyGeodata Cloud).

Keyhole Markup Language (KML) is a file format used to display geographic data in an application reminiscent of Google Earth. It uses a tag-based structure with nested elements and attributes and relies on the XML standard (Google, 2023).

The structure of my input data looks as shown within the image below. It incorporates five different trade relationships between neighboring countries: Nepal-India, Nepal-Bangladesh, Nepal-China, India-Pakistan, and India-Sri Lanka. For every country pair, there are 4 coordinate points for the beginning and end points of the 2 arrows. Value1 represents the export from Country1 to Country2. Value2 represents the import by Country1 from Country2. The aim is to display this relationship in a Python map.

Data input for trade flow maps. Image by Creator.

I read the above data as a pandas dataframe df. Moreover, I created dictionary objects reminiscent of transfers containing the export and import volume between each country pair, and startarrow1_dict containing the coordinate of start line of the primary arrow.

Creating essential dictionary objects. Image by Creator.

On this section, I’ll describe the code used to visualise the trade flow maps. I’ll mainly use the matplotlib and cartopy packages. I actually have also used the identical packages to visualise the worldwide surface temperature anomaly in considered one of my previous posts.

  1. Import required packages

I began with importing the foremost required packages and dependencies as shown below:

import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib import colormaps
from matplotlib.colours import Normalize
from matplotlib.cm import ScalarMappable

import numpy as np
import pandas as pd
import os

2. Read the form file

As a shape file, I used the Natural Earth Vector. The vector file may be read directly by the shapereader module of the cartopy package.

# get the country border file (10m resolution) and extract
shpfilename = shpreader.natural_earth(
resolution=”10m”,
category=”cultural”,
name=”admin_0_countries”,
)
reader = shpreader.Reader(shpfilename)
countries = reader.records()

Using a package called Fiona, it is feasible to read the list of all countries as shown below.

Fiona package is used to open the form file and extract the list of all country names. Image by Creator.

3. Extract the data of only required countries

Next, I created required, which is an inventory of six countries having trade relationships. I also created a dictionary object c, which contained the FionaRecord i.e., all relevant information of the countries that may be used for plotting.

# required countries
required = [“Nepal”, “India”, “Bangladesh”,”China”,”Pakistan”,”Sri Lanka”]

# extract the precise country information
c = {
co.attributes["ADMIN"]: co
for co in countries if co.attributes["ADMIN"] in required
}

4. Plot the required countries and clipping

On this step, first, I plotted the geometries of required countries in a PlateCarree projection as shown below:

Plotting the required countries. Image by Creator.

Next, I desired to clip off the geometries of the remaining of the world in order that I could have a magnified view of the six countries alone. I decided the extent of the utmost and minimum longitude and latitude values respectively that would cover all six countries, set the extent for the axes plot, and plotted the countries. Within the for loop, I also added an code that will display the names of the countries over the centroid geometry of every country.

The zorder attribute of the matplotlib package would determine the drawing order of the artists. Artists with higher zorder are drawn on the highest.

# get overall boundary box from country bounds
extents = np.array([c[cn].bounds for cn in c])
lon = [extents.min(0)[0], extents.max(0)[2]]
lat = [extents.min(0)[1], extents.max(0)[3]]

ax = plt.axes(projection=ccrs.PlateCarree())

# get country centroids
ax.set_extent([lon[0] - 1, lon[1] + 1, lat[0] - 1, lat[1] + 1])

for key, cn in zip(c.keys(),c.values()):
ax.add_geometries(cn.geometry,
crs=ccrs.PlateCarree(),
edgecolor="gray",
facecolor="whitesmoke",
zorder = 1)

# Add country names
centroid = cn.geometry.centroid

ax.text(
centroid.x,
centroid.y,
key, # Assuming 'name' is the attribute containing the country names
horizontalalignment='center',
verticalalignment='center',
transform=ccrs.PlateCarree(),
fontsize=8, # Adjust the font size as needed
color='black', # Set the colour of the text
zorder = 2
)

plt.axis("off")
plt.show()

5. Arrange colormap, add arrow patches, and color bar.

That is crucial section of the code. First, I chosen viridis_r i.e., the reverse color palette of viridis as my colormap. Next, I decided the minimum and maximum value of any trade values between countries as tmin and tmax respectively. These values are normalized such that the tmin corresponds to the bottom end (0) and tmax corresponds to the very best end (1) of the colormap cmap and used accordingly within the succeeding code.

Then I looped through the transfers and used the FancyArrowPatch object to plot the arrows between countries. Each arrow object is related to a singular color col that represents the trade flow from one country to a different. While it’s also possible to make use of an offset from the coordinates of the primary arrow to plot the second arrow, I actually have specified the coordinates for the second arrow in my code. Within the code, the mutation_scale attribute is used to manage the length of the top of the arrow, and the linewidth attribute is used to manage the width of the foremost line.

Finally, I added the horizontal colorbar below the foremost plot.

ax = plt.axes(projection=ccrs.PlateCarree())

# get country centroids
ax.set_extent([lon[0] - 1, lon[1] + 1, lat[0] - 1, lat[1] + 1])

for key, cn in zip(c.keys(),c.values()):
ax.add_geometries(cn.geometry,
crs=ccrs.PlateCarree(),
edgecolor="grey",
facecolor="whitesmoke",
zorder = 1)

# Add country names
centroid = cn.geometry.centroid

ax.text(
centroid.x,
centroid.y,
key, # Assuming 'name' is the attribute containing the country names
horizontalalignment='center',
verticalalignment='center',
transform=ccrs.PlateCarree(),
fontsize=8, # Adjust the font size as needed
color='black', # Set the colour of the text
zorder = 2
)

# arrange a colormap
cmap = colormaps.get("viridis_r")
tmin = np.array([v for v in transfers.values()]).min()
tmax = np.array([v for v in transfers.values()]).max()
norm = Normalize(tmin, tmax)

for tr in transfers:
c1, c2 = tr.split(",")
startarrow1 = startarrow1_dict[tr]
endarrow1 = endarrow1_dict[tr]

startarrow2 = startarrow2_dict[tr]
endarrow2 = endarrow2_dict[tr]

t1 = transfers[tr][0]
col = cmap(norm(t1))

# Use the arrow function to attract arrows
arrow = mpatches.FancyArrowPatch(
(startarrow1[0], startarrow1[1]),
(endarrow1[0], endarrow1[1]),
mutation_scale=20, #control the length of head of arrow
color=col,
arrowstyle='-|>',
linewidth=2, # You'll be able to adjust the linewidth to manage the arrow body width
zorder = 3
)
ax.add_patch(arrow)

#OTHER WAY
offset = 1
t2 = transfers[tr][1]
col = cmap(norm(t2))
arrow = mpatches.FancyArrowPatch(
(startarrow2[0], startarrow2[1]),
(endarrow2[0], endarrow2[1]),
mutation_scale=20,
color=col,
arrowstyle='-|>',
linewidth=2, # You'll be able to adjust the linewidth to manage the arrow body width
zorder = 4
)
ax.add_patch(arrow)

sm = ScalarMappable(norm, cmap)
fig = plt.gcf()
cbar = fig.colorbar(sm, ax=ax,
orientation = "horizontal",
pad = 0.05, #distance between foremost plot and colorbar
shrink = 0.8, #control length
aspect = 20 #control width
)
cbar.set_label("Trade flow")

plt.title("Trade flow in South Asia")
plt.axis("off")

plt.savefig("trade_flow2_with_labels.jpeg",
dpi = 300)
plt.show()

The top product is shown below. In my dummy dataset, the least trade flow is export from Sri Lanka to India (53 units), which is represented by yellow color. The very best trade flow is export from Bangladesh to Nepal (98 units), which is represented by violet color.

Bi-directional trade flow between countries represented by arrows between countries. Image by Creator.

On this post, I demonstrated how the trade flow between countries including export and import relationships may be visualized in a Python map using two arrows. I actually have used the cartopy and matplotlib packages for this purpose. Within the second a part of this series, I’ll showcase how the “net” trade flow relationship may be visualized while highlighting the online exporter and net importer countries.

The notebook for this post is on the market on this GitHub repository. Thanks for reading!

References

Google Developers, 2023. KML Tutorial | Keyhole Markup Language | Google for Developers. The content of this page is licensed under the Creative Commons Attribution 4.0 License

LEAVE A REPLY

Please enter your comment!
Please enter your name here