Learn how to use Dash Bio for next-gen sequencing & quality control. 🧬 Register for the Oct 27 webinar.

Using Plotly to Generate Interpolated Heatmap from Location

Input file: CSV containing temperature, latitude, and longitude

.

I am want to generate a “heat map” of temperatures using plotly. I thought I used the z-field correctly (temperature) From the error message below, it looks like I will need to generate a numpy array for lat, lon, and temperature, but I am still somewhat new to this… Any suggestions?

Error Message after executing:

The 'z' property is an array that may be specified as a tuple,
    list, numpy array, or pandas Series

Code:

#!/usr/bin/env python3
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from argparse import ArgumentParser
from pathlib import Path

HELP_SCREEN = "This is a tool to map out sign concentration interactively through a map\
You will need to install plotly in your local machine. To do so; \
Please execute: pip3 install plotly"


def parse_args():
    """
    Arguments for retrieving input csv file
    """
    parser = ArgumentParser(description=HELP_SCREEN)
    parser.add_argument(
        "--input-csvfile",
        # Notice, we declare this arguent as a Path.
        type=Path,
        required=True,
        help="Enter CSV File"
    )
    parser.add_argument("--region", 
        type=str, 
        required=False,
        default=' ',
        help="This is NOT required. If this is for a certain region, please specify country"
        )

    return parser.parse_args()

def main():
    '''
    main function to interactively map sign density from csv
    '''
    options = parse_args()
    region = options.region
    if region=='':
        region = ''
    else:
     region = options.region
    df = pd.read_csv(options.input_csvfile)
    print(df)
    print(df.columns)
    df.rename(columns={' L1Latitude': 'latitude', 'L1Longitude': 'longitude', '_2M_TMP_K,': 'temp'}, inplace=True)
    
    fig = go.Figure(go.Densitymapbox(lat=df.latitude, 
        lon=df.longitude, z='temp',
        radius=5,
        colorbar=dict(
        title="Wind",
        titleside="top",
        tickmode="array",
        tickvals=[-3, 3],
        ticktext=["Sparse", "Dense"],
        ticks="outside"
        )
    ))
    fig.update_layout(
        title="TEST " + region,
        titlefont=dict(
            family="Courier New, monospace",
            size=20,
            color="#7f7f7f"
        )
    )
    fig.update_layout(
    mapbox_style="white-bg",
    mapbox_layers=[
        {
            "below": 'traces',
            "sourcetype": "raster",
            "source": [
                "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}.png"
            ]
            
        }
      ])

    '''Basemap settings. We can later store certain lat,lon coordinates into a list that the user feeds in the 
    region argument. As a result, we can set map to a specific area. If left alone, we could just set mapbox center
    to a default central location somewhere on earth such as longitude 180
    '''
    fig.update_layout(mapbox_style="open-street-map",
        width=1200,
        height=750,
        mapbox_center_lon=4.2,
        mapbox_center_lat=50.8,
        mapbox=dict(zoom=7))
    fig.show()
    with open('plotly_graph.html', 'w') as f:
        f.write(fig.to_html(include_plotlyjs='cdn'))


if __name__ == '__main__':
    main()