Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jupyter-naas
GitHub Repository: jupyter-naas/awesome-notebooks
Path: blob/master/Dash/Dash_Plotly_Dynamic_Link.ipynb
2973 views
Kernel: Python 3

Dash.png

Dash - Plotly Dynamic Link

Give Feedback | Bug report

Tags: #dash #plotly #naas #analytics

Last update: 2023-04-12 (Created: 2022-10-18)

Description: This notebook provides an interactive way to explore data with Dash and Plotly, allowing users to create dynamic links between visualizations.

Input

Import libraries

import os try: import dash except: !pip install dash --user import dash try: import dash_bootstrap_components as dbc except: !pip install dash_bootstrap_components --user import dash_bootstrap_components as dbc import webbrowser from dash.dependencies import Input, Output from dash import html, dcc from dash.exceptions import PreventUpdate import plotly.express as px import plotly.graph_objects as go

Setup Variables

DASH_PORT = 8050

Model

Initialize Dash app

app = dash.Dash( requests_pathname_prefix=f'/user/{os.environ.get("JUPYTERHUB_USER")}/proxy/{DASH_PORT}/', external_stylesheets=[dbc.themes.BOOTSTRAP], meta_tags=[ {"name": "viewport", "content": "width=device-width, initial-scale=1.0"} ], ) # if you are not in Naas # app = dash.Dash()

Get stock prices

df = px.data.stocks() # reading stock price dataset print("Data fetched:", len(df)) df.head()

Add an url column

# add a url for each stock in the dataset into urls column df["urls"] = "https://www.naas.ai/" df.head()

Create app layout

app.layout = html.Div( id="parent", children=[ html.H1( id="H1", children="Dynamic link on label click on plotly chart python", style={"textAlign": "center", "marginTop": 40, "marginBottom": 40}, ), dcc.Graph( id="line-plot", figure=px.line( data_frame=df, x="date", y="GOOG", title="Google stock prices over time", hover_name="urls", custom_data=("urls",), ), ), dcc.Store(id="clientside-data", data=""), dcc.Store(id="redirected-url", data=""), ], )

Call callback function to save url in a dcc Store component when data point is clicked

@app.callback(Output("clientside-data", "data"), [Input("line-plot", "clickData")]) def open_url(clickData): if clickData != None: print(clickData) url = clickData["points"][0]["customdata"][0] return url else: raise PreventUpdate

Call client-side callback function open url in a new tab

app.clientside_callback( """ function(data,scale) { console.log(data); window.open(data, '_blank'); return data; } """, Output("redirected-url", "data"), Input("clientside-data", "data"), )

Output

Generate URL and show logs

if __name__ == "__main__": app.run_server(proxy=f"http://127.0.0.1:{DASH_PORT}::https://app.naas.ai")