How to open a URL by clicking a data point in Python Plotly?


Plotly supports two different libraries "Plotly graphs in a Dash app" and "Plotly Graph objects and Plotly Express".

Dash is a Python framework and it is used to create interactive web-based dashboard applications. For example, dash library adds all the required libraries to web-based dashboard applications.

Import dash core components and HTML components. Add plotly.express method to generate graphs. Use the Dcc.Graph() method to set the style for height and width coordinates.

Follow the steps given below to open a URL by clicking a data point.

Step 1

Import the Dash library.

import dash

Step 2

Import the Dash core components, dcc and html.

from dash import dcc, html

Step 3

Import Dash dependencies using the below module

from dash.dependencies import Input,Output

Step 4

Import plotly.express module and alias as px

import plotly.express as px

Step 5

Generate a dataset using the pandas module. Let us generate a dataset using the following method and add URLs inside the dataframe dictionary.

df = pd.DataFrame(
   dict(
      x=[1, 2],
      y=[2, 4],
      urls=["https://www.tutorialspoint.com","https://plotly.com/dash/"],
   )
)

Step 6

Generate the scatter plot using the URL coordinates,

fig = px.scatter(df, x="x", y="y",custom_data=["urls"])

Step 7

Create the update_layout() method to perform even click and set traces for the marker size. It is defined below,

fig.update_layout(clickmode='event+select')
fig.update_traces(marker_size=20)

Step 8

Generate app layout for HTML children in div sections. It is defined below,

app.layout = html.Div([
   dcc.Graph(
      id="graph_interaction",
      figure=fig,
   ),
   html.Pre(id='data')
])

Step 9

Generate the function for "url onclick" event. We will also set an "if" condition to perform browser onclick event. It is defined below,

@app.callback(
   Output('data', 'children'),
   Input('graph_interaction', 'clickData'))

def open_url(clickData):
   if clickData:

webbrowser.open(clickData["points"][0]["customdata"][0])
   else:
      raise PreventUpdate

Step 10

Create main function to run the server.

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

Example

The complete code to open a URL by clicking a data point in Plotly is as follows −

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
import json

app = dash.Dash(__name__)
df = pd.DataFrame(
   dict(
      x=[1, 2],
      y=[2, 4],
      urls=["https://www.tutorialspoint.com","https://plotly.com/dash/"],
   )
)
fig = px.scatter(df, x="x", y="y",custom_data=["urls"])
fig.update_layout(clickmode='event+select')
fig.update_traces(marker_size=20)

app.layout = html.Div(
   [
      dcc.Graph(
         id="graph_interaction",
         figure=fig,
      ),
      html.Pre(id='data')
   ]
)

@app.callback(
   Output('data', 'children'),
   Input('graph_interaction', 'clickData'))
def open_url(clickData):
   if clickData:
   webbrowser.open(clickData["points"][0]["customdata"][0
])
   else:
      raise PreventUpdate
      # return json.dumps(clickData, indent=2)
      
if __name__ == '__main__':
   app.run_server(debug=True)

Output

It will show the following output on the console.

Dash is running on http://127.0.0.1:8050/

 * Serving Flask app 'main'
 * Debug mode: on

Click on the URL and it will display the output on the browser −


If you click on the node, it will be redirected to the given URL link.

Updated on: 07-Oct-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements