Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to open a URL by clicking a data point in Python Plotly?
In Python Plotly with Dash, you can create interactive scatter plots where clicking a data point opens a specific URL. This is achieved by storing URLs as custom data and using Dash callbacks to handle click events.
Setting Up the Dashboard
First, import the required libraries and create a Dash application ?
import webbrowser import dash from dash.exceptions import PreventUpdate from dash import dcc, html from dash.dependencies import Input, Output import plotly.express as px import pandas as pd # Create Dash app app = dash.Dash(__name__)
Creating Data with URLs
Create a DataFrame containing coordinates and corresponding URLs ?
# Create sample data with URLs
data = pd.DataFrame({
'x': [1, 2, 3, 4],
'y': [2, 4, 1, 5],
'urls': [
"https://www.tutorialspoint.com",
"https://plotly.com/dash/",
"https://pandas.pydata.org/",
"https://numpy.org/"
],
'labels': ['TutorialsPoint', 'Plotly Dash', 'Pandas', 'NumPy']
})
print(data)
x y urls labels 0 1 2 https://www.tutorialspoint.com TutorialsPoint 1 2 4 https://plotly.com/dash/ Plotly Dash 2 3 1 https://pandas.pydata.org/ Pandas 3 4 5 https://numpy.org/ NumPy
Creating the Interactive Plot
Generate a scatter plot with custom data containing the URLs ?
# Create scatter plot with custom data
fig = px.scatter(
data,
x="x",
y="y",
text="labels",
custom_data=["urls"]
)
# Configure plot for click events
fig.update_layout(clickmode='event+select')
fig.update_traces(marker_size=15, textposition="top center")
Complete Dashboard Example
Here's the complete code that creates a clickable scatter plot dashboard ?
import webbrowser
import dash
from dash.exceptions import PreventUpdate
from dash import dcc, html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
# Create Dash app
app = dash.Dash(__name__)
# Create sample data with URLs
data = pd.DataFrame({
'x': [1, 2, 3, 4],
'y': [2, 4, 1, 5],
'urls': [
"https://www.tutorialspoint.com",
"https://plotly.com/dash/",
"https://pandas.pydata.org/",
"https://numpy.org/"
],
'labels': ['TutorialsPoint', 'Plotly Dash', 'Pandas', 'NumPy']
})
# Create scatter plot
fig = px.scatter(
data,
x="x",
y="y",
text="labels",
custom_data=["urls"]
)
# Configure plot settings
fig.update_layout(
clickmode='event+select',
title="Click on Points to Open URLs"
)
fig.update_traces(marker_size=15, textposition="top center")
# Define app layout
app.layout = html.Div([
dcc.Graph(
id="clickable_graph",
figure=fig,
),
html.Div(id='click_info', style={'margin-top': '20px'})
])
# Callback to handle clicks
@app.callback(
Output('click_info', 'children'),
Input('clickable_graph', 'clickData')
)
def open_url_on_click(clickData):
if clickData:
# Extract URL from custom data
url = clickData["points"][0]["customdata"][0]
# Open URL in browser
webbrowser.open(url)
return f"Opening: {url}"
else:
raise PreventUpdate
# Run the app
if __name__ == '__main__':
app.run_server(debug=True)
When you run this code, it will start a local server and display the following output ?
Dash is running on http://127.0.0.1:8050/ * Serving Flask app '__main__' * Debug mode: on
How It Works
The dashboard works through these key components:
-
Custom Data: URLs are stored as
custom_datain the scatter plot -
Click Mode:
clickmode='event+select'enables click event detection -
Callback Function: The
@app.callbackdecorator handles click events -
URL Opening:
webbrowser.open()launches URLs in the default browser
Key Features
| Feature | Purpose | Implementation |
|---|---|---|
| Custom Data | Store URLs with points | custom_data=["urls"] |
| Click Detection | Enable point clicking | clickmode='event+select' |
| Callback | Handle click events | @app.callback |
| URL Opening | Launch browser | webbrowser.open() |
Conclusion
Creating clickable data points in Plotly Dash requires storing URLs as custom data and implementing a callback function to handle click events. This approach enables interactive dashboards where users can navigate to different websites by clicking on chart elements.
