Plotly Dynamic Link
Tags: #dash #plotly #naas #analytics
Description: This notebook provides an interactive way to explore data with Dash and Plotly, allowing users to create dynamic links between visualizations.
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
DASH_PORT = 8050
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()
df = px.data.stocks() # reading stock price dataset
print("Data fetched:", len(df))
df.head()
# add a url for each stock in the dataset into urls column
df["urls"] = "https://www.naas.ai/"
df.head()
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=""),
],
)
@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
app.clientside_callback(
"""
function(data,scale) {
console.log(data);
window.open(data, '_blank');
return data;
}
""",
Output("redirected-url", "data"),
Input("clientside-data", "data"),
)
if __name__ == "__main__":
app.run_server(proxy=f"http://127.0.0.1:{DASH_PORT}::https://app.naas.ai")
Last modified 1mo ago