How to use a custom png image marker in a plot (Matplotlib)?

To use a custom PNG or JPG image as a marker in a plot, we can use Matplotlib's OffsetImage and AnnotationBbox classes. This technique allows you to place images at specific coordinates instead of traditional point markers.

Required Components

The key components for image markers are ?

  • OffsetImage: Converts image files into plottable objects

  • AnnotationBbox: Positions images at specific coordinates

  • Image paths: List of image file locations

  • Coordinates: X and Y positions for each image

Example

Here's how to create a plot with custom image markers ?

import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import numpy as np

# Set figure size
plt.rcParams["figure.figsize"] = [8, 6]
plt.rcParams["figure.autolayout"] = True

def getImage(path, zoom=0.1):
    """Load and return an OffsetImage object"""
    return OffsetImage(plt.imread(path), zoom=zoom)

# Sample data points
x_coords = [1, 3, 5, 7, 9]
y_coords = [2, 6, 3, 8, 4]

# Create sample images (you would use your actual image paths)
# For demo purposes, creating colored squares
fig, ax = plt.subplots(figsize=(10, 6))

# Create some sample data to demonstrate
colors = ['red', 'blue', 'green', 'orange', 'purple']

for i, (x, y, color) in enumerate(zip(x_coords, y_coords, colors)):
    # Create a small colored square as demo image
    img_array = np.ones((20, 20, 3))
    if color == 'red':
        img_array[:,:] = [1, 0, 0]
    elif color == 'blue':
        img_array[:,:] = [0, 0, 1]
    elif color == 'green':
        img_array[:,:] = [0, 1, 0]
    elif color == 'orange':
        img_array[:,:] = [1, 0.5, 0]
    else:
        img_array[:,:] = [0.5, 0, 1]
    
    # Create OffsetImage and AnnotationBbox
    offset_img = OffsetImage(img_array, zoom=0.8)
    annotation_box = AnnotationBbox(offset_img, (x, y), frameon=False)
    ax.add_artist(annotation_box)

# Customize the plot
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_xlabel('X Coordinate')
ax.set_ylabel('Y Coordinate')
ax.set_title('Custom Image Markers in Matplotlib')
ax.grid(True, alpha=0.3)

plt.show()

Using Actual Image Files

If you have actual PNG or JPG files, use this approach ?

import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox

def create_image_plot(image_paths, x_coords, y_coords, zoom=0.1):
    """Create a plot with custom image markers"""
    fig, ax = plt.subplots(figsize=(10, 6))
    
    for x, y, path in zip(x_coords, y_coords, image_paths):
        # Load image and create OffsetImage
        img = OffsetImage(plt.imread(path), zoom=zoom)
        
        # Create AnnotationBbox and add to plot
        ab = AnnotationBbox(img, (x, y), frameon=False)
        ax.add_artist(ab)
    
    # Set axis limits and labels
    ax.set_xlim(min(x_coords)-1, max(x_coords)+1)
    ax.set_ylim(min(y_coords)-1, max(y_coords)+1)
    ax.set_xlabel('X Position')
    ax.set_ylabel('Y Position')
    ax.grid(True, alpha=0.3)
    
    return fig, ax

# Example usage
image_files = ['icon1.png', 'icon2.png', 'icon3.png']
x_positions = [2, 5, 8]
y_positions = [3, 7, 4]

# Create the plot
fig, ax = create_image_plot(image_files, x_positions, y_positions, zoom=0.15)
plt.show()

Key Parameters

Parameter Description Example Values
zoom Controls image size 0.1, 0.5, 1.0
frameon Shows/hides border around image True, False
pad Padding around the image 0.1, 0.5

Common Use Cases

  • Geographic plots: Using country flags or location icons

  • Product analysis: Displaying product images on scatter plots

  • Sports analytics: Team logos on performance charts

  • Scientific visualization: Custom symbols for different categories

Conclusion

Custom image markers enhance data visualization by replacing standard markers with meaningful images. Use OffsetImage to load images and AnnotationBbox to position them precisely on your plots.

Updated on: 2026-03-25T21:47:13+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements