How to highlight a given country in a matplotlib plot of multiple countries?
May 11, 8:53pm
To highlight a specific country in a matplotlib plot (e.g., a world map or a choropleth map), you can use the following approach:
Steps to Highlight a Country
Use geopandas and matplotlib to plot the countries.
Filter the country you want to highlight.
Plot all countries in a base color.
Overlay the highlighted country in a different color.
Example Code
Here’s a practical example using geopandas and matplotlib:
python
import geopandas as gpd
import matplotlib.pyplot as plt
# Load a world map dataset
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
# Select the country to highlight (e.g., France)
country_to_highlight = 'France'
highlighted_country = world[world['name'] == country_to_highlight]
# Plot all countries in light gray
ax = world.plot(color='lightgray', edgecolor='black', figsize=(10, 6))
# Overlay the highlighted country in red
highlighted_country.plot(ax=ax, color='red', edgecolor='black')
# Customize the plot
plt.title(f"Highlighted Country: {country_to_highlight}")
plt.axis('off') # Remove axis
plt.show()
Key Points
geopandas is used to handle geographic data.
world.plot() plots all countries in a base color.
highlighted_country.plot(ax=ax, ...) overlays the selected country in a different color.
plt.axis('off') removes the axis for a cleaner look.
Alternative: Using cartopy (for more advanced maps)
If you need more control (e.g., projections), you can use cartopy:
python
import cartopy.io.img_tiles as cimgt
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
# Create a figure with a plate carree projection
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
# Add coastlines and countries
ax.coastlines()
ax.add_feature(cartopy.feature.BORDERS, linestyle=':')
ax.add_feature(cartopy.feature.COUNTRY_BORDERS, linestyle='-')
# Highlight France (example)
ax.add_geometries(
[world[world['name'] == 'France'].geometry.iloc[0]],
ccrs.PlateCarree(),
facecolor='red',
edgecolor='black'
)
plt.title("Highlighted Country: France")
plt.show()
May 11, 8:53pm
This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.