Skip to content

Instantly share code, notes, and snippets.

@hbshrestha
Created December 15, 2023 20:42
Show Gist options
  • Save hbshrestha/356aebdd5536577d3616850479debbe2 to your computer and use it in GitHub Desktop.
Save hbshrestha/356aebdd5536577d3616850479debbe2 to your computer and use it in GitHub Desktop.
visualizing trade flow in Python maps Part I
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 color of the text
zorder = 2
)
# set up 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 draw 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 can adjust the linewidth to control 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 can adjust the linewidth to control 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 main 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment