How to set Plotly map marker color based on if condition?

Hello,

I have a dataframe with lat, lon, and value. If the value is 0 I want blue, if it is >20 red and if <20 green.

Is it possible to use something like this function? If yes, how can I include this in the color field of Plotly so it takes the df[‘value’] as an input?

def SetColor():
      if(x == 0):
           return "blue"
     elif(x > 20):
          return "red"
    elif(x<20):
        return "green"
import plotly.express as px

fig = px.scatter_mapbox(us_cities, lat="lat", lon="lon", zoom=3, height=300)
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

That function will work in a modified sense. I would just pass the entire data and create a list of blue, red, green. You can then just pass that list to a color argument in the code of a go.Scattermapbox. See below:

        fig = go.Figure()

        fig.add_trace(go.Scattermapbox(
                lat=df['lat'].tolist(),
                lon=df['lng'].tolist(),
                mode='markers',
                marker=go.scattermapbox.Marker(
                    size=4,
                    color='#E31837' #list or singular color here
                ),
                #text = df['personal_lastName'].tolist(),
                hoverinfo='none',
            )
        )

Where would be the part of the color selection there? Can I pass the df[‘value’] column to color?

This is what your function should look like. You’ll pass in your data frame, and get a list of the column you want to color base on

def SetColor(df):
    values = df[column].tolist()
    color_list = []
    for i in values:
        if(i == 0):
            color_list.append("blue")
        elif(i > 20):
            color_list.append("red")
        elif(i<20):
            color_list.append("green")
    return color_list

Then you’ll call that function to return your list of colors.

        fig = go.Figure()

        fig.add_trace(go.Scattermapbox(
                lat=df['lat'].tolist(),
                lon=df['lng'].tolist(),
                mode='markers',
                marker=go.scattermapbox.Marker(
                    size=4,
                    color= SetColor(df)  #function gets called here and will return a list of colors, (i.e. ['green', 'blue', 'red', 'green'])
                ),
            )
        )
1 Like