Plot data on the whole map

Hello,
I am new to Plotly and i am wondering if there is any way to plot data on a map object such as go.Scattergeo() with projection_type="natural earth". Not scatterpoints or choropleths but on the whole map maybe as a heatmap or contour.

Something like this:

Thank you !

Hey @alex1000,

Welcome to the community.

You can plot your data as a contour but as far as I know you need to install geojsoncontour package.

https://pypi.org/project/geojsoncontour/

Here’s an example:

DATA:

x	y	z
26.7750	38.3250	118.0000
26.8250	38.3250	228.0000
26.8250	38.3750	334.0000
26.8750	38.3250	334.0000
26.8750	38.3750	416.0000
26.9250	38.3250	554.0000
26.9250	38.3750	416.0000
26.9250	38.4250	224.0000
26.9750	38.3750	415.0000
26.9750	38.4250	544.0000
27.0250	38.3750	112.0000
27.0250	38.4250	119.0000
27.0250	38.4750	554.0000
27.0750	38.3750	817.0000
27.0750	38.4250	925.0000
27.0750	38.4750	120.0000
27.1250	38.3750	317.0000
27.1250	38.4250	244.0000
27.1250	38.4750	137.0000
27.1750	38.3750	884.0000
27.1750	38.4250	842.0000
27.1750	38.4750	635.0000
27.2250	38.4250	720.0000
27.2250	38.4750	522.0000
27.2750	38.4250	114.0000

CODE:

import numpy as np
import pandas as pd
from scipy.interpolate import griddata
#
import json
import geojsoncontour
#
import plotly.graph_objs as go
import matplotlib.pyplot as plt
import matplotlib as mpl


#Read data
data = pd.read_csv('data.txt', header=0, delimiter='\t')

#Create meshgrid for x,y
xi = np.linspace(min(data['x']), max(data['x']), num=100)
yi = np.linspace(min(data['y']), max(data['y']), num=100)

x_grid, y_grid = np.meshgrid(xi,yi)

#Grid data
z_grid = griddata((data['x'],data['y']),data['z'],(x_grid,y_grid),method='cubic')

#Mpl contourf
cs=plt.contourf(x_grid,y_grid,z_grid,cmap=plt.cm.jet)
plt.colorbar(cs)
plt.show()

# Convert matplotlib contourf to geojson
geojson = geojsoncontour.contourf_to_geojson(contourf=cs)
my_geojson = json.loads(geojson)


#Filling array with Z and Id for each geojson spatial object. Z value from contour plot will be stored as title
arr_temp=np.ones([len(my_geojson["features"]),2])

for i in range(0, len(my_geojson["features"])):

    my_geojson["features"][i]["id"]=i

    arr_temp[i,0]=i
    arr_temp[i,1]=my_geojson["features"][i]["properties"]["title"].split("-")[0]

df_contour=pd.DataFrame(arr_temp, columns=["Id","Z"])   
    

   
fig = go.Figure(go.Choropleth ( locations=df_contour.Id,
                                z= df_contour.Z,
                                colorscale="jet",
                                geojson= my_geojson) )

fig.update_layout(geo = dict(projection = dict(type = 'natural earth')))
fig.show()

OUTPUT:

Useful Links:

https://www.tjansson.dk/2018/10/contour-map-in-folium/
https://towardsdatascience.com/visualizing-spatial-data-with-geojson-heatmaps-1fbe2063ab86
https://stackoverflow.com/questions/69443849/adding-geojson-contours-as-layers-on-plotly-density-mapbox

Have a nice day.

2 Likes