Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13981

Converting Matplotlib's filled contour plot (contourf_plot) to GeoJSON

$
0
0

I am working on a project where I have successfully generated filled contour plots using plt.contourf in Matplotlib in a Google Colab environment. Now, I am attempting to convert these filled contour polygons into GeoJSON for seamless integration with Folium.

import numpy as npimport foliumfrom folium import pluginsimport matplotlib.pyplot as pltfrom matplotlib.colors import to_hex, Normalize# Specify the URL of the NetCDF fileurl = "https://www.star.nesdis.noaa.gov/socd/mecb/sar/AKDEMO_products/APL_winds/tropical/2024/SH052024_BELAL/STAR_SAR_20240116013937_SH052024_05S_MERGED_FIX_3km.nc"# Download the NetCDF file contentresponse = requests.get(url)nc_content = BytesIO(response.content)# Open the NetCDF file using xarraydataset = xr.open_dataset(nc_content)# Access the 'sar_wind' variablesar_wind = dataset['sar_wind'].values# Access the 'latitude' and 'longitude' variableslatitude = dataset['latitude'].valueslongitude = dataset['longitude'].values# Set iso values for filled contoursiso_values_filled = np.linspace(np.min(sar_wind), np.max(sar_wind), 11)  # One extra value for filling the background# Create a filled contour plotcontourf_plot = plt.contourf(longitude, latitude, sar_wind, levels=iso_values_filled, cmap='viridis')# Convert filled contour polygons to GeoJSONgeojson_data_polygon = {"type": "FeatureCollection", "features": []}# Normalize iso values for colormap mappingnorm = Normalize(vmin=np.min(iso_values_filled), vmax=np.max(iso_values_filled))for level, collection in zip(iso_values_filled, contourf_plot.collections):    for path in collection.get_paths():        coordinates = path.vertices.tolist()        # Close the polygon by repeating the first vertex        coordinates.append(coordinates[0])        color_hex = to_hex(plt.cm.viridis(norm(level)))  # Map normalized iso value to colormap        geojson_data_polygon["features"].append({"type": "Feature","geometry": {"type": "Polygon","coordinates": [coordinates]            },"properties": {"level": level,"color": color_hex            }        })# Create a Folium map centered on the average latitude and longitudecenter_lat, center_lon = np.mean(latitude), np.mean(longitude)mymap_polygon = folium.Map(location=[center_lat, center_lon], zoom_start=8)# Add filled contour polygons as GeoJSON overlay with colored areasfolium.GeoJson(    geojson_data_polygon,    style_function=lambda feature: {'fillColor': feature['properties']['color'],'color': feature['properties']['color'],'weight': 2,'fillOpacity': 0.7    }).add_to(mymap_polygon)# Display the map with filled contour polygonsmymap_polygon

Issue:

contourf_plot gives this map, which the desired result.enter image description here

but the folium gives:

enter image description here

We can see that the polygons are not built.

Objective:My goal is to convert the filled contour polygons from contourf_plot into GeoJSON format so that I can display them in Folium.


Viewing all articles
Browse latest Browse all 13981

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>