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
Selected Reading
Matplotlib – Plot over an image background in Python
To plot over an image background in Matplotlib, you can overlay plots on top of images using imshow() and standard plotting functions. This technique is useful for data visualization on maps, annotating images, or creating custom backgrounds for plots.
Steps to Plot Over an Image
- Read an image from a file into an array using
plt.imread() - Create a figure and subplot with
plt.subplots() - Display the image using
imshow()with specified extent - Create your plot data and overlay it using standard plotting methods
- Display the final result with
plt.show()
Example
Here's how to create a sample image and plot a line over it −
import numpy as np
import matplotlib.pyplot as plt
# Configure figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
# Create a sample image (gradient background)
width, height = 300, 300
x_grad = np.linspace(0, 1, width)
y_grad = np.linspace(0, 1, height)
X, Y = np.meshgrid(x_grad, y_grad)
sample_image = np.sqrt(X**2 + Y**2)
# Create figure and axis
fig, ax = plt.subplots()
# Display the image as background
im = ax.imshow(sample_image, extent=[0, 300, 0, 300], cmap='viridis', alpha=0.7)
# Create data to plot over the image
x = np.array(range(300))
y = x # Diagonal line
# Plot over the image
ax.plot(x, y, linestyle='dotted', linewidth=3, color='red', label='Diagonal Line')
ax.plot(x, 300-x, linestyle='dashed', linewidth=2, color='white', label='Anti-diagonal')
# Add labels and legend
ax.set_xlabel('X Coordinate')
ax.set_ylabel('Y Coordinate')
ax.set_title('Plot Over Image Background')
ax.legend()
plt.show()
Key Parameters
| Parameter | Purpose | Example Value |
|---|---|---|
extent |
Sets image coordinates | [0, 300, 0, 300] |
alpha |
Image transparency | 0.7 (70% opaque) |
cmap |
Color mapping | 'viridis', 'gray' |
Working with Real Images
For external image files, use the following approach −
import matplotlib.pyplot as plt
import numpy as np
# Read external image file
im = plt.imread("your_image.jpg")
# Create figure and display image
fig, ax = plt.subplots()
ax.imshow(im, extent=[0, 300, 0, 300])
# Plot data over the image
x = np.linspace(0, 300, 100)
y = 150 + 50 * np.sin(x / 30) # Sine wave
ax.plot(x, y, linewidth=3, color='yellow', alpha=0.8)
plt.show()
Common Use Cases
- Geographic Data: Plotting routes or data points on maps
- Image Analysis: Overlaying measurement lines on scientific images
- Custom Backgrounds: Using artistic images as plot backgrounds
- Data Annotation: Adding explanatory graphics to existing images
Conclusion
Use imshow() with appropriate extent parameters to display background images, then overlay standard plots using normal Matplotlib functions. Adjust transparency and colors to ensure your plot data remains visible against the image background.
Advertisements
