To highlight a specific country in a matplotlib plot (e.g., a world map or a choropleth map), you can use the following approach:
geopandas and matplotlib to plot the countries.Here’s a practical example using geopandas and matplotlib:
pythonimport 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()
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.cartopy (for more advanced maps)If you need more control (e.g., projections), you can use cartopy:
pythonimport 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()
Le Chat can make mistakes. Check answers. Learn more