Search code examples
pythonplotly-python

Plotly.express density_heatmap radius values based on z value


I'm working with plotly.express and the density_mapbox function. Here's my code:

fig = px.density_mapbox(calc_data, lat='latitude', lon='longitude', size='calc_dis_m', radius=10, mapbox_style="stamen_terrain")
fig.show()

It plots fine, but what I'm wondering is that if it's possible to make it so that the dots radii are based on the calc_dis_m values in my dataframe. That way, the dots will have radii equal to their value, so that the smaller calc_dis_m values are smaller on the map and the bigger values are bigger.

Is this possible within the density_mapbox function?


Solution

  • Yes, you can assign different radius for each point by assigning a list of numbers between [1, inf]. For instance, in the code below, I assign a list of numbers between 1 and 10:

    radius=df.Magnitude.tolist()
    

    Code:

    import pandas as pd
    import numpy as np
    import plotly.express as px
    
    df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv')
    
    df['Magnitude'] = np.random.rand(len(df))*10 + 1 # change the default value 
    
    fig = px.density_mapbox(df, lat='Latitude', lon='Longitude', z='Magnitude', radius=df.Magnitude.tolist(),
                            center=dict(lat=0, lon=180), zoom=0,
                            mapbox_style="stamen-terrain")
    fig.show()
    

    Output:

    enter image description here

    Notes:

    As you see in the map above, each point has different size based on the radius.