Search code examples
pythonplotly

How to set scatter map marker color based on condition?


I have a dataframe with lat, lon, name, value. I want to plot a map where the markers have a different color based on condition of the value. If value < 20 then color green, if value > 20 then color red. I found something online and implemented it marker=dict(color=np.where(np.logical_and(df['value'].values < 20, 20 >= df['value'].values), 'blue', 'green')) but it does only show every marker in green instead of the ones above 20 in red. Any idea how I can solve this?

Dataframe:

name        lat         lon      value
BELAL01     51.23619    4.38522  12
BELHB23     51.1703     4.341    16
BELLD01     51.10998    5.00486  28
BELLD02     51.12038    5.02155  11
BELR833     51.32766    4.36226  45
BELSA04     51.31393    4.40387  87
BELWZ02     51.1928     5.22153  12
BETM802     51.26099    4.4244   16
fig = go.Figure(go.Scattermapbox(
    mode = "markers",
    lon = df['lon'],
    lat = df['lat'],
    marker=dict(
        color=np.where(np.logical_and(df['value'].values < 20, 20 >= df['value'].values), 'blue', 'green')
    )

))
fig.update_layout(mapbox_style="open-street-map")
fig.show()

Solution

  • If you change the marker line to show red and green by changing the marker line in your code...

    marker=dict(
            color=np.where(np.logical_and(df['value'].values < 20, 20 >= df['value'].values), 'red', 'green')
        )
    

    you can get the plot as below (5 reds and 3 greens)...

    enter image description here

    You can check the ones in red/green like this

    np.where(np.logical_and(df['value'].values < 20, 20 >= df['value'].values), 'red', 'green')

    which gives...

    array(['red', 'red', 'green', 'red', 'green', 'green', 'red', 'red'], dtype='<U5')