PyGMT library in Python made plotting high-resolution topographic maps a breeze. It comes packaged with shorelines, country borders and topographic data. Often, we need to highlight an arbitrarily selected polygon shapes or region on a map using available shapefile data.
In this post, we will see how we can overlay shapefile data on top of the PyGMT map using geopandas library. Here, for example, I obtained the counties data available in .shp format from data.gov.tw, and overlay it on the high-resolution map of Taiwan.
GeoData Format
When you unarchive the obtained shapefile data, you will see three types of formats with the same filename:
geofile.shp: contains actual geometry datageofile.dbf: contains attributes for each shapegeofile.shx: contains index to record offsets. Useful for working with large shapefile data.
Import libraries
We will use the geopandas library to read the .shp files.
import pygmt
import os
import geopandas as gpd
Counties .shp data
I download the shp data from counties and saved it in countiesData in the working directory. There are multiple files in the countiesData, but we only need the COUNTY_MOI_1090820.shp file. Others are related extention files.
We selected the two counties to highlight on the map – Taipei City, Tainan City.
countiesShp = os.path.join("countiesData","COUNTY_MOI_1090820.shp")
gdf = gpd.read_file(countiesShp)
all_data = []
all_data.append(gdf[gdf["COUNTYENG"]=="Taipei City"])
all_data.append(gdf[gdf["COUNTYENG"]=="Tainan City"])
Plot basemap using PyGMT
Now, we can plot the simple basemap using PyGMT. The benefit of using PyGMT is that we don’t need the coastlines and topographic data separately and the output is high-resolution.
region = [119, 123, 21, 26]
fig = pygmt.Figure()
fig.basemap(region=region, projection="M4i", frame=True)
fig.coast(
water='skyblue',
shorelines=True)
Overlay the counties
Now, we can overlay the selected counties, fill them with green color, and then put all other counties with the background color (white).
for data_shp in all_data:
fig.plot(data=data_shp,color="green")
fig.plot(data=countiesShp)
Save the map in raster and vector format
Now, we can save the map in raster and vector format for later use.
fig.savefig('map1.png')
fig.savefig('map1.pdf')

Topographic map
Instead of using simple white as background (which btw looks quite descent to me), we can use the topographic background:
import pygmt
import os
import geopandas as gpd
countiesShp = os.path.join("countiesData","COUNTY_MOI_1090820.shp")
gdf = gpd.read_file(countiesShp)
all_data = []
all_data.append(gdf[gdf["COUNTYENG"]=="Taipei City"])
all_data.append(gdf[gdf["COUNTYENG"]=="Tainan City"])
region = [119, 123, 21, 26]
fig = pygmt.Figure()
fig.basemap(region=region, projection="M4i", frame=True)
fig.grdimage("@srtm_relief_03s", shading=True, cmap='geo')
fig.coast(
water='skyblue',
shorelines=True)
for data_shp in all_data:
fig.plot(data=data_shp,color="white", pen=["0.02c", 'white'])
fig.plot(data=countiesShp, pen=["0.02c", 'white'])
fig.savefig('map1.png')
fig.savefig('map1.pdf')


Plotting North America maps
Now, let us plot the map of NA using the combination of geopandas and PyGMT. You can obtain the shapefile data from the NOAA website.
Reading data
Here, we use the geopandas provided dataset. But the steps are similar for datasets from any other sources.
import os
import geopandas as gpd
import pygmt
import matplotlib.pyplot as plt
dataShp = os.path.join("GSHHS_shp","f","GSHHS_f_L1.shp")
# gdf = gpd.read_file(dataShp)
gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
print(gdf.columns)
# print(gdf['source'].unique())
print(gdf.head())
# print(len(gdf))
print(gdf.crs) #“EPSG:4326” WGS84 Latitude/Longitude, used in GPS
# gdf = gdf.to_crs("EPSG:3395") #Spherical Mercator. Google Maps, OpenStreetMap, Bing Maps
Extract data for North America
Now, we use the Continents column of the geopandas dataframe to extract the data for North America.
na_gdf = gdf[gdf['continent'] == 'North America']
Plotting map using geopandas plot method
First we plot the map using the geopandas plot method.
fig, ax = plt.subplots(1, 1)
na_gdf.boundary.plot(ax=ax, color="#555555", linewidth=1)
# na_gdf.plot(ax=ax, color="#555555", linewidth=1)
plt.savefig('north-america-geopandas-map.png',bbox_inches='tight',dpi=300)
plt.close('all')

Plotting map using PyGMT
Now, we plot the map using the PyGMT.
# Define geographical range
minlon, maxlon = -180, -20
minlat, maxlat = 0, 90
fig = pygmt.Figure()
fig.basemap(region=[minlon, maxlon, minlat, maxlat], projection="Poly/4i", frame=True)
fig.plot(data=na_gdf,color="blue")
fig.savefig("north-america-pygmt-map.png", crop=True, dpi=300, transparent=True)

Conclusions
We have seen two cases (Taiwan and North America) of how to easily add the shapefile data on top of the PyGMT map. We plotted the counties data on top of the basemap of Taiwan. Furthermore, we created a high-resolution topographic map with shapefile data overlayed on it.







Sprawdź oficjalną aplikację z licencją Totalizatora — do 10 000 zł + darmowe spiny! Pełna legalność z oficjalną licencją — wejdź i zacznij grać i odbierz bonus! Oficjalna aplikacja Totalizatora oferuje bonus do 13 750 zł — wszystko w pełni legalnie. Legalna rozrywka — Totalizator Sportowy zapewnia bezpieczeństwo danych i regularne promocje. Szukasz legalnego salonu gier? Oficjalna aplikacja z licencją daje Ci start z dopłatą — zarejestruj się i zacznij! Zaufaj oficjalnemu operatorowi — Aplikacja z licencją oferuje do 550 darmowych spinów i bezpieczeństwo płatności. Zacznij grę bezpiecznie — pobierz aplikację i odbierz swój bonus!
[url=https://hackmd.io/@coffee-breaks/HyYNcFlzWe]hackmd.io[/url]
w5zr2c
Мы делаем вебсайты, которые привлекают клиентов и увеличивают продажи.
Почему стоит выбрать нас?
Качественный дизайн, который удерживает взгляд
Адаптация под любые устройства (ПК, смартфоны, планшеты)
SEO-оптимизация для роста в поисковых системах
Скорость работы — никаких медленных страниц
Специальное предложение:
Первым 4 клиентам — дисконт 8% на разработку сайта!
Готовы обсудить проект?
Позвоните нам!
[url=https://glavtorgspecsnabsbit.shop/]Сайт студии glavtorgspecsnabsbit[/url]
Justly, I’m obsessed with these CBD gummies like [url=https://www.cornbreadhemp.com/collections/thc-drinks ]best thc drinks[/url] ! I’ve tried a lot of brands, but these are legit the best. I pop song after a long prime and it ethical helps me chill out and stop overthinking everything.
They swallow like existing bon-bons no odd grassy flavor at all. My take a nap has been fail elevate surpass since I started taking them, too. If you’re on the quibble, exactly fetch them! They’re a comprehensive lifesaver as a remedy for my routine stress.
Искал, как класть кафель в санузле. На одних сайтах — банальные советы, на других — целые трактаты с кучей ненужных шагов. Случайно наткнулся на базу с нормальными ресурсами, с реальными советами профессионалов без этой ерунды. Вот, может кому пригодится
[url=https://domodomiknash.xyz/]Сайт[/url]
I’ve been using [url=https://www.nothingbuthemp.net/collections/thc-chocolate ]Delta 9 Bar[/url] regular in regard to all about a month now, and I’m indubitably impressed at near the sure effects. They’ve helped me feel calmer, more balanced, and less anxious throughout the day. My saw wood is deeper, I wake up refreshed, and even my pinpoint has improved. The value is distinguished, and I worth the sensible ingredients. I’ll categorically heed buying and recommending them to everybody I know!
Truthfully, I’m obsessed with these CBD gummies! I’ve tried a spray of brands, but these are legit the best. I crack at one after a yearn broad daylight and it straight helps me frosty out and an end overthinking everything.
They desire like true to life sweetmeats no peculiar grassy flavor at all. My catch forty winks has been way happier since I started captivating them, too. If you’re on the indecisive, honourable go for them! They’re a sum total lifesaver with a view my daily stress.
wonderful submit, very informative. I ponder why the
other specialists of this sector don’t notice this.
You should continue your writing. I am sure, you’ve a great readers’ base already!
很难找到, 这么生动的旅行故事。你们最棒。
Пытался найти, как сделать облицовку в ванной. Где-то — «главное — ровный слой», а в других — многостраничные инструкции с 20 этапами подготовки. Пока не обнаружил подборку где нет воды, где мастера с опытом объясняют по делу. Держите, если актуально
[url=https://domodomiknash.xyz/]Сайт[/url]
Заливал тёплые полы — перечитал кучу советов в интернете. В одних источниках советуют «делайте стяжку 6 см», то «можно обойтись 3 см». В итоге обнаружил портал, где систематизировали нормальные ресурсы: с действующими нормативами, советами мастеров и без сомнительных экспертов. Теперь хоть понимаю, какой вариант верный
[url=https://domodomiknash.xyz/]domodomiknash[/url]
⭐ Najważniejsze:
– Największa biblioteka gier
– Wypłaty BLIK w 5 minut – średnio 4 min 37 sek!
– Pakiet powitalny 2000 PLN + 50 spinów gratis
– Darmowe wpłaty i wypłaty – każda złotówka dla Ciebie
– VIP Club z przywilejami
– Gwarancje:
– BLIK – depozyty i wypłaty
– Niski próg wejścia
– Szyfrowanie 256-bit SSL
– Licencja MF RP
Promocje:
– Cashback 10% co tydzień
– Pule nagród 200k
– Promocje daily
– Wydarzenia specjalne
Wydajność:
– Tylko 43 MB
– Android 6.0+ i iOS 11+
– Test bez ryzyka
– Support całodobowy
Odpowiedzialna gra:
Ustaw limity – przypomnienia + pauza.
Zagraj już dziś w [url=https://www.weddingbee.com/members/laneyalorski/]pierwszym legalnym kasynie[/url] i startuj z premią!
18+ Graj odpowiedzialnie.
⭐ Najważniejsze:
– Największa biblioteka gier
– Najszybsze wypłaty w Polsce – średnio 4 min 37 sek!
– Bonus 100% do 2000 PLN + 50 free spins
– Darmowe wpłaty i wypłaty – każda złotówka dla Ciebie
– 6 poziomów VIP z nagrodami
Płatności:
– Pełna integracja z BLIK
– Start od 20 zł
– Ochrona jak w bankach
– Regulacje prawne
Promocje:
– Cotygodniowy cashback
– Pule nagród 200k
– Reload bonusy
– Misje sezonowe
Technologia:
– Tylko 43 MB
– Szeroka kompatybilność
– Graj za darmo
– Support całodobowy
Kontrola:
Graj odpowiedzialnie – limity depozytów + samowykluczenie.
Zagraj już dziś w [url=https://dev.to/nepixesgurtebver]lotto kasyno pl[/url] i startuj z premią!
Tylko dla pełnoletnich.
[url=https://wakelet.com/@CoxaferLirsto50787]Totalizator Kasyno[/url] – jedyne legalne kasyno online w PL! Wypłaty BLIK 5 min. Darmowe transakcje. 100% bezpieczne. Zagraj teraz!
Quick review! Playing the mega moolah app for a few weeks – here’s what I found.
Best parts:
– Interac sign-in – super fast KYC
– Four jackpots – Mini, Minor, Major, Mega (starts at CA$2M)
– Any bet qualifies – low stakes trigger jackpot
– 24h withdrawals – I got paid in under a day
– Demo mode – test unlimited
My result:
– Put in CA$50 (Interac e-Transfer)
– Hit Minor pot: CA$1,240
– Withdrew – paid in 18h
– Total: +CA$890
Responsible gaming:
Must set daily limits before play. System locks at limit.
Download: Find [url=https://wakelet.com/@RarodobBistro60540]mega moolah app[/url] in Google Play
Gamble responsibly!
Хочу розказати історією, яка пригодилася у мене того самого тижня, і це було…. Дочка вимовила бажання, аби ваша покірна слуга створила один неймовірно красиве до день народження. Я, звичайно, розпочала шукати варіант у інтернеті і – уявіть!. Втратила цілісних 1.5 години марних пошуків, переходячи з сайту до черговий кулінарний портал! Перші варіанти були занадто складні, інші варіанти – зі справжніми недоступними інгредієнтами, ще кілька – із надмірною кількістю банерів. Але як грім серед ясного неба ваша героїня мені спало на думку про існування сей чудовий сайт та менш ніж за п’ять неймовірно швидких хвилинок вишукала – мрійливий рецепт! Інструкція був настільки настільки зрозумілим, що в результаті навіть моя ще дуже молода помічниця змогла мені взяти участь. Як результат наша команда спекли ніби з журналу торт, який виявився головним успіхом свята. Вже сьогодні усі мої найкращі подруги обсіли мене з розпитуваннями: “На якому сайті ти знайшла такий ідеальний варіант?”
[url=https://uadomodeas.xyz/]Блог кулінарних рецептів[/url]
I tried a not many products from Tillmans Tranquils – [url=https://www.tillmanstranquils.com/collections/delta-9-thc-mints ]thc mint[/url] and really liked the inclusive experience. The gummies contain a cleansed know, smooth texture, and in harmony quality. The flavors sensible of fundamental, and the portioned servings up it comfortable to on what works for you. Their packaging looks premium and the total feels thoughtfully made. A downright make with products that are enjoyable and reliable.
Hi! Tested the mega moolah app for a few weeks – this is the scoop.
Highlights:
– 60-second verification – instant KYC
– Four jackpots – Mini, Minor, Major, Mega (starts at CA$2M)
– CA$0.25 minimum – low bets qualify for jackpot
– Fast cashouts – I got paid in 18 hours
– Free play – test risk-free
Personal test:
– Put in CA$50 (Interac e-Transfer)
– Landed Minor pot: CA$1,240
– Cashed out – paid in 18h
– Net: +CA$890
Responsible gaming:
Must set loss caps before first spin. App locks at limit.
Install: Search [url=https://myanimelist.net/profile/YehogerMathew]mega moolah app[/url] in Google Play
Gamble responsibly!
Раніше думала, що відмінно знаю як готувати, але останнім часом мої страви стали одноманітними і повторювалися. Подружка підказала мені подивитися оригінальні рецепти, але я не знала, як підібрати. Випадково в інтернеті знайшла цей каталог і… це було справжнє одкровення! Виявилося, що є величезна кількість сайтів з незвичайними рецептами, про які я навіть уяви не мала. Я була в захваті від розділи з фірмовими стравами та рецептами різних кухонь світу. Протягом місяця я спробувала страву мексиканської кухні, тайської та навіть іспанської кухні! Моя сім’я в захваті, а я відчуваю себе повноцінним кулінаром. Навіть почала вести щоденник, де записую цілі кулінарні відкриття, які вдалося приготувати
[url=https://uadomodeas.xyz/]Сайт рецептів uadomodeas[/url]
I tried a two products from Tillmans Tranquils – [url=https://www.tillmanstranquils.com/collections/delta-9-thc-mints ]thc mint[/url] and actually liked the overall experience. The gummies have a straighten up taste, slick texture, and in harmony quality. The flavors feel reasonable, and the portioned servings make it easy to choose what works in return you. Their packaging looks premium and everything feels thoughtfully made. A unshakeable brand with products that are enjoyable and reliable.
Мы создаем вебсайты, которые привлекают клиентов и увеличивают продажи.
Почему стоит выбрать нас?
Стильный дизайн, который цепляет взгляд
Адаптация под все устройства (ПК, смартфоны, планшеты)
SEO-оптимизация для продвижения в поисковых системах
Скорость работы — никаких “тормозящих” страниц
Специальное предложение:
Первым 4 клиентам — дисконт 19% на разработку сайта!
Готовы обсудить проект?
Позвоните нам!
[url=https://opadalli.icu/]Сайт студии Opadalli[/url]
我关注这样的资源, 这里有真诚的评论。这个页面 就是 关于这些的。加油。 [url=https://iqvel.com/zh-Hans/a/%E5%8D%B0%E5%BA%A6/%E9%98%BF%E6%A0%BC%E6%8B%89%E5%A0%A1]沙賈漢被囚[/url] 我很少遇到, 这么高质量的内容。谢谢。
I’ve been exploring [url=https://terpenewarehouse.com/collections/indica-terpenes ]indica terpenes[/url] recently, and I’m deep down enjoying the experience. The scents are well off, natural, and pleasant. They add a gracious be a match for to my always routine, helping set the willing and atmosphere. A brobdingnagian find to save anyone who appreciates pungent wellness tools.