Skip to content

scattermapbox plot doesn't update with change in pandas dataframe in a callback #3631

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
kevalshah90 opened this issue Mar 15, 2022 · 15 comments
Labels
bug something broken

Comments

@kevalshah90
Copy link

I am slicing a pandas dataframe based on user input. While the callback runs and I see that the dataframe is updated, the changes aren't reflected on the map. I am passing a pandas series at lat and lon and the map should be updated with the DataFrame. Below is simplified version of my code:



import dash_bootstrap_components as dbc 
import dash
from dash import dcc
import pandas as pd

import plotly.express as px

df = px.data.carshare()


layout = html.Div([ 

                                  dcc.Graph(id="map"),
                                  dbc.Input(id='input'), 
                                  dbc.Button("Apply", id="show", className="mr-1", n_clicks=0)

               ]) 

# Update map graph
@app.callback(Output("map", "figure"),
                          [

                            Input("Input", "value"),
                            Input("show", "n_clicks")

                         ],
                        )
def update_map(input, btn_nclick):

    # check for triggered inputs / states
    ctx = dash.callback_context

    data = []

    if input:

       df = df[df['peak_hour'] == 11]

       data.append({

                        "type": "scattermapbox",
                        "lat": df['centroid_lat'],
                        "lon": df['centroid_lon'],
                        "mode": "markers",
                        "marker": {
                      
                                            "symbol": "circle",
                                            "size": 9,
                                            "opacity": 0.8,
                     
                            }
                     }
        )

       layout = {

                 "autosize": True,
                 "datarevision": 0,
                 "hovermode": "closest",
                 "mapbox": {

                     "accesstoken": MAPBOX_KEY,
                     "bearing": 0,
                     "center": {
                         "lat": coords[0],
                         "lon": coords[1]
                     },
                     "pitch": 0,
                     "opacity": 0.2,
                     "zoom": zoom,
                     "style": "streets",

                 },

                 "margin": {
                    "r": 0,
                    "t": 0,
                    "l": 0,
                    "b": 0,
                    "pad": 0
                }

    }

   return ({"data": data, "layout": layout})

Trying to wrap my head around why the map not being updated with change in pandas DataFrame.

@Coding-with-Adam
Copy link
Contributor

Coding-with-Adam commented Jan 30, 2023

A similar issue was reported by Yaseen, a community member.

The code renders a button and a dcc.Graph whose figure is a go.Figure with a trace of go.Scattermapbox.

The purpose is to generate markers (in random locations). The number of makers should match the number of clicks.

The issue is that the figure data gets updated in the callback, yet the new markers are not rendered.
Weirdly enough, you can still hover over them as shown in this screenshot:

import pandas as pd
import plotly.graph_objects as go
import numpy as np
import dash
from dash import dcc, html, Input, Output, callback, State


def generate_map(N):
    fig = go.Figure()
    df = pd.DataFrame({"lat":np.random.random(N), "lon":np.random.random(N)})

    fig.add_trace(
        go.Scattermapbox(lat=df.lat, lon=df.lon, mode="markers", marker=dict(size=15, color="red"))
    )

    fig.layout.update(title={
        'xanchor': 'center',
        'yanchor': 'top'
    },
        showlegend=False,
        margin={
            "r": 0,
            "t": 0,
            "l": 0,
            "b": 0
        },
        mapbox=go.layout.Mapbox(
            uirevision="foo",
            style="carto-positron",
            zoom=3,
            center_lat= np.random.random(),
            center_lon= np.random.random(),
        ))

    return fig




app = dash.Dash(__name__)
app.layout = html.Div(
    children=[
        html.Button("Click me",id="btn",n_clicks=0),
              dcc.Graph(id="orders-map",
                        style=dict(height="100%",width="100%"))]
)



@callback(
    Output("orders-map","figure"),
    Input("btn","n_clicks"),
    State("orders-map","figure")
)
def update_map(n_clicks, old_figure):
    print(f"updated using {n_clicks}")
    if old_figure:
        print("Old data:", old_figure['data'])
    new_figure = generate_map(n_clicks)
    print("New data:", new_figure['data'])
    return new_figure


if __name__ == '__main__':
    app.run_server(debug=True, port=9090)

image

@Coding-with-Adam
Copy link
Contributor

Comment from the community member:

I double-checked and I confirm that the example above works with dash==2.6.1 and dash==2.6.2
It does not work, however, with dash>=2.7.0.

@vprzybylo
Copy link

I ran into this same issue with the hover updating but the scatter points in the previous location and switching from dash==2.7.0 to dash==2.8.1 solved it.

@kevalshah90
Copy link
Author

kevalshah90 commented Feb 2, 2023

@vprzybylo good to know. what's your plotly.js version? I am getting the issue with vdash==2.8.1

@vprzybylo
Copy link

I'm using plotly==5.11.0 in python

@archmoj
Copy link
Contributor

archmoj commented Feb 9, 2023

I ran into this same issue with the hover updating but the scatter points in the previous location and switching from dash==2.7.0 to dash==2.8.1 solved it.

Thanks @vprzybylo.
@kevalshah90 could you please try latest plotly.py or dash==2.8.1 and possibly close the issue if resolved?

@kevalshah90
Copy link
Author

kevalshah90 commented Feb 10, 2023

It is not working for me with dash==2.8.1 and plotly==5.11.0 | 5.13.0, the latest version of plotly. It works for me with dash==2.6.2

@vprzybylo @archmoj

@archmoj
Copy link
Contributor

archmoj commented Feb 10, 2023

@kevalshah90 thanks for trying that out.
This is likely a bug in plotly.js.
To help us debug the issue,
would you please make a codepen using your setup as described here: plotly/plotly.js#6444 (comment) ?

@archmoj archmoj added the bug something broken label Feb 10, 2023
@fontempa
Copy link

fontempa commented Mar 4, 2023

Is there any update regarding this issue? I've been having the exact same problem since last week, and been struggling for two days until I came with this post. I made the test with dash==2.7.0, then dash==2.8.1, and then dash==2.6.2 and gives me the same results: the figure actually gets updated, but the markers are not (however, you can hover over them and see the info of it)

@artdreamer
Copy link

I'm experiencing the same issue, and I hope someone can help me resolve it. Upon further investigation, I believe this may be related to the recent introduction of the cluster effect in Dash 2.7.0. In addition, I noticed another issue related to the cluster effect: enabling it for scatter plot traces makes the restyleData property valid.

@tomboehling
Copy link

fyi: plotly/plotly.js#6444 (comment)

@Coding-with-Adam
Copy link
Contributor

This bug has been fixed in the latest version of Dash (v2.10.2).

@wknjk
Copy link

wknjk commented Jul 16, 2023

In version 2.11.1 of Dash, the dataframe is not being updated when clustering is set to True. However, it works properly when clustering is set to False.

@ruaridht
Copy link

ruaridht commented Oct 3, 2023

Regarding the specific issue referenced in the above comment: #3631 (comment)

The update appears to work for me in Dash v2.12.1 and not in v2.13.0. Does anyone else also experience this issue again ?

@Coding-with-Adam
Copy link
Contributor

hey @ruaridht
I just upgraded Dash to v2.13.0 and I don't get the bug on my windows machine. The code from comment #3631 works just fine for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug something broken
Projects
None yet
Development

No branches or pull requests

9 participants