How to display an image on hovering over a point in Python Plotly?

Plotly is a powerful visualization library that allows you to create interactive plots with hover effects. In this tutorial, we'll learn how to display images when hovering over data points using Plotly with Dash.

Prerequisites

First, install the required libraries ?

pip install plotly dash pandas

Understanding the Approach

To display images on hover, we need three key components:

  • Custom data Store image URLs in the plot data
  • Hover callback Detect when user hovers over points
  • Dynamic image display Update the image source based on hover data

Complete Example

Here's a complete working example that displays different animal images when hovering over scatter plot points ?

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__)

# Set image URLs
dog_image = "https://images.unsplash.com/photo-1552053831-71594a27632d?w=300&h=200&fit=crop"
cat_image = "https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?w=300&h=200&fit=crop"
bird_image = "https://images.unsplash.com/photo-1444464666168-49d633b86797?w=300&h=200&fit=crop"

# Create sample data
df = pd.DataFrame({
    'x': [1, 2, 3],
    'y': [2, 4, 3],
    'animal': ['Dog', 'Cat', 'Bird'],
    'images': [dog_image, cat_image, bird_image]
})

# Create scatter plot
fig = px.scatter(df, x="x", y="y", 
                 hover_name="animal",
                 custom_data=["images", "animal"])

# Customize plot appearance
fig.update_traces(marker=dict(size=15, color='lightblue', 
                             line=dict(width=2, color='darkblue')))
fig.update_layout(
    title="Hover over points to see images",
    xaxis_title="X Coordinate",
    yaxis_title="Y Coordinate",
    hovermode='closest'
)

# Define app layout
app.layout = html.Div([
    html.H1("Image Display on Hover Example", 
            style={'textAlign': 'center', 'color': '#2c3e50'}),
    
    dcc.Graph(
        id="scatter-plot",
        figure=fig,
        style={'height': '500px'}
    ),
    
    html.Div([
        html.H3("Hovered Image:", style={'color': '#34495e'}),
        html.Img(id='hover-image', 
                src='', 
                style={'maxWidth': '300px', 'maxHeight': '200px', 
                      'border': '2px solid #3498db'})
    ], style={'textAlign': 'center', 'marginTop': '20px'})
])

# Callback function for hover interaction
@app.callback(
    Output('hover-image', 'src'),
    Input('scatter-plot', 'hoverData')
)
def display_hover_image(hover_data):
    if hover_data:
        # Extract custom data from hover event
        custom_data = hover_data["points"][0]["customdata"]
        return custom_data[0]  # Return image URL
    else:
        return ''  # Return empty string when not hovering

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

How It Works

Step 1: We create a DataFrame with coordinates and image URLs stored in a custom data column.

Step 2: The scatter plot includes custom_data parameter to attach image URLs to each point.

Step 3: The callback function listens for hoverData events and extracts the image URL from the custom data.

Step 4: When hovering occurs, the image source is dynamically updated to display the corresponding image.

Key Components

Component Purpose Key Parameter
custom_data Store additional data with plot points custom_data=["images"]
hoverData Capture hover events Input('plot', 'hoverData')
html.Img Display dynamic images id='image', src=''

Output

When you run the application, it will display:

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

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

The browser will show an interactive scatter plot. When you hover over different points, corresponding animal images will appear below the plot.

Customization Options

You can enhance this example by:

  • Adding tooltips Use hover_name and hover_data parameters
  • Styling images Apply CSS styles to the image container
  • Multiple image sources Support local files or base64-encoded images
  • Error handling Add fallback images for broken URLs

Conclusion

Displaying images on hover in Plotly requires combining custom data storage, hover event detection, and dynamic image updates. This technique creates engaging interactive visualizations that can display additional context or media when users explore data points.

---
Updated on: 2026-03-26T22:26:38+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements