Inside the commerce transfer maps, I aimed to represent two-way commerce relationships between nations. As an example, the export from Nepal to India could possibly be represented by the first arrow (A1-A2) and the import by Nepal from India could possibly be represented by a second arrow (A3-A4). On this strategy, each nation pair relationship would require 4 coordinate elements to stipulate the start and end elements of arrows to represent exports and imports respectively.
Whereas it’s additionally doable to think about a coordinate that could be detected mechanically (for example, the centroid of a country geometry), I meant to mark the elements in a map and get their coordinates individually. For this operate, it’s doable to create a problem in an utility akin to Google Earth, export a KML file, and extract the coordinates with a converter (for example, the GIS info converter throughout the website online of MyGeodata Cloud).
Keyhole Markup Language (KML) is a file format used to point out geographic info in an utility akin to Google Earth. It makes use of a tag-based development with nested elements and attributes and depends on the XML commonplace (Google, 2023).
The development of my enter info appears as confirmed throughout the image beneath. It incorporates 5 completely totally different commerce relationships between neighboring nations: Nepal-India, Nepal-Bangladesh, Nepal-China, India-Pakistan, and India-Sri Lanka. For each nation pair, there are 4 coordinate elements for the start and end elements of the two arrows. Value1 represents the export from Country1 to Country2. Value2 represents the import by Country1 from Country2. The aim is to point out this relationship in a Python map.
I be taught the above info as a pandas dataframe df
. Furthermore, I created dictionary objects akin to transfers
containing the export and import amount between each nation pair, and startarrow1_dict
containing the coordinate of begin line of the first arrow.
On this half, I’ll describe the code used to visualise the commerce transfer maps. I’ll primarily use the matplotlib and cartopy packages. I’ve moreover used the equivalent packages to visualise the worldwide ground temperature anomaly in one of my earlier posts.
- Import required packages
I started with importing the first required packages and dependencies as confirmed beneath:
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreaderimport matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib import colormaps
from matplotlib.colors import Normalize
from matplotlib.cm import ScalarMappable
import numpy as np
import pandas as pd
import os
2. Study the shape file
As a kind file, I used the Pure Earth Vector. The vector file could possibly be be taught straight by the shapereader module of the cartopy bundle.
# get the nation border file (10m choice) and extract
shpfilename = shpreader.natural_earth(
choice=”10m”,
class=”cultural”,
title=”admin_0_countries”,
)
reader = shpreader.Reader(shpfilename)
nations = reader.knowledge()
Using a bundle often known as Fiona, it’s doable to be taught the guidelines of all nations as confirmed beneath.
3. Extract the data of solely required nations
Subsequent, I created required
, which is an inventory of six nations having commerce relationships. I moreover created a dictionary object c
, which contained the FionaRecord i.e., all associated data of the nations that may be utilized for plotting.
# required nations
required = [“Nepal”, “India”, “Bangladesh”,”China”,”Pakistan”,”Sri Lanka”]# extract the actual nation data
c = {
co.attributes["ADMIN"]: co
for co in nations if co.attributes["ADMIN"] in required
}
4. Plot the required
nations and clipping
On this step, first, I plotted the geometries of required
nations in a PlateCarree projection as confirmed beneath:
Subsequent, I wanted to clip off the geometries of the rest of the world so that I might need a magnified view of the six nations alone. I made up my thoughts the extent of the utmost and minimal longitude and latitude values respectively which may cowl all six nations, set the extent for the axes plot, and plotted the nations. Inside the for loop, I moreover added an code that may present the names of the nations over the centroid geometry of each nation.
The zorder
attribute of the matplotlib bundle would determine the drawing order of the artists. Artists with better zorder
are drawn on the best.
# get common boundary area from nation 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 nation 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 nation names
centroid = cn.geometry.centroid
ax.textual content material(
centroid.x,
centroid.y,
key, # Assuming 'title' is the attribute containing the nation names
horizontalalignment="center",
verticalalignment="center",
rework=ccrs.PlateCarree(),
fontsize=8, # Regulate the font dimension as needed
shade="black", # Set the color of the textual content material
zorder = 2
)
plt.axis("off")
plt.current()
5. Organize colormap, add arrow patches, and shade bar.
That’s essential a part of the code. First, I chosen viridis_r
i.e., the reverse shade palette of viridis
as my colormap. Subsequent, I made up my thoughts the minimal and most price of any commerce values between nations as tmin
and tmax
respectively. These values are normalized such that the tmin
corresponds to the underside end (0) and tmax
corresponds to the easiest end (1) of the colormap cmap
and used accordingly throughout the succeeding code.
Then I looped by the transfers
and used the FancyArrowPatch object to plot the arrows between nations. Each arrow object is said to a singular shade col
that represents the commerce transfer from one nation to a special. Whereas it’s additionally doable to utilize an offset from the coordinates of the first arrow to plot the second arrow, I’ve specified the coordinates for the second arrow in my code. Inside the code, the mutation_scale
attribute is used to handle the scale of the highest of the arrow, and the linewidth
attribute is used to handle the width of the first line.
Lastly, I added the horizontal colorbar beneath the first plot.
ax = plt.axes(projection=ccrs.PlateCarree())# get nation 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 nation names
centroid = cn.geometry.centroid
ax.textual content material(
centroid.x,
centroid.y,
key, # Assuming 'title' is the attribute containing the nation names
horizontalalignment="center",
verticalalignment="center",
rework=ccrs.PlateCarree(),
fontsize=8, # Regulate the font dimension as needed
shade="black", # Set the color of the textual content material
zorder = 2
)
# prepare 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.minimize up(",")
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 carry out to draw arrows
arrow = mpatches.FancyArrowPatch(
(startarrow1[0], startarrow1[1]),
(endarrow1[0], endarrow1[1]),
mutation_scale=20, #administration the scale of head of arrow
shade=col,
arrowstyle="-|>",
linewidth=2, # You'll regulate the linewidth to handle the arrow physique 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,
shade=col,
arrowstyle="-|>",
linewidth=2, # You'll regulate the linewidth to handle the arrow physique 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 main plot and colorbar
shrink = 0.8, #administration dimension
facet = 20 #administration width
)
cbar.set_label("Commerce transfer")
plt.title("Commerce transfer in South Asia")
plt.axis("off")
plt.savefig("trade_flow2_with_labels.jpeg",
dpi = 300)
plt.current()
The highest product is confirmed beneath. In my dummy dataset, the least commerce transfer is export from Sri Lanka to India (53 gadgets), which is represented by yellow shade. The perfect commerce transfer is export from Bangladesh to Nepal (98 gadgets), which is represented by violet shade.
On this submit, I demonstrated how the commerce transfer between nations along with export and import relationships could possibly be visualized in a Python map using two arrows. I’ve used the cartopy and matplotlib packages for this operate. Inside the second part of this assortment, I’ll showcase how the “net” commerce transfer relationship could possibly be visualized whereas highlighting the online exporter and net importer nations.
The pocket guide for this submit is on the market on this GitHub repository. Thanks for learning!
References
Google Builders, 2023. KML Tutorial | Keyhole Markup Language | Google for Developers. The content material materials of this net web page is licensed beneath the Creative Commons Attribution 4.0 License
Thank you for being a valued member of the Nirantara family! We appreciate your continued support and trust in our apps.
- Nirantara Social - Stay connected with friends and loved ones. Download now: Nirantara Social
- Nirantara News - Get the latest news and updates on the go. Install the Nirantara News app: Nirantara News
- Nirantara Fashion - Discover the latest fashion trends and styles. Get the Nirantara Fashion app: Nirantara Fashion
- Nirantara TechBuzz - Stay up-to-date with the latest technology trends and news. Install the Nirantara TechBuzz app: Nirantara Fashion
- InfiniteTravelDeals24 - Find incredible travel deals and discounts. Install the InfiniteTravelDeals24 app: InfiniteTravelDeals24
If you haven't already, we encourage you to download and experience these fantastic apps. Stay connected, informed, stylish, and explore amazing travel offers with the Nirantara family!
Source link