Overlaying data on images helps you see extra information on top of pictures. It makes it easier to understand patterns or highlight important parts.
0
0
Overlaying data on images in Matplotlib
Introduction
You want to show points or lines on a photo, like marking locations on a map.
You need to compare data with a background image, like showing weather data on a satellite image.
You want to highlight areas of interest on a medical scan.
You want to add labels or markers on a chart that uses an image as background.
Syntax
Matplotlib
import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('image.png') plt.imshow(img) plt.plot(x_values, y_values, 'ro') # example: red dots plt.show()
plt.imshow() shows the image.
plt.plot() adds data points or lines on top.
Examples
This example shows blue dots at two points on the image.
Matplotlib
import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('image.png') plt.imshow(img) plt.plot([50, 100], [30, 80], 'bo') # blue dots plt.show()
This example draws a green line between two points on the image.
Matplotlib
import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('image.png') plt.imshow(img) plt.plot([20, 80], [40, 90], 'g-') # green line plt.show()
This example uses scatter to add yellow points on the image.
Matplotlib
import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('image.png') plt.imshow(img) plt.scatter([60, 120], [50, 100], color='yellow') # yellow scatter points plt.show()
Sample Program
This program creates a gray image and overlays red points and a blue line on it. It shows how to combine image display and data plotting.
Matplotlib
import matplotlib.pyplot as plt import numpy as np # Create a simple image (a gray square) img = np.full((100, 100), 0.7) # gray background plt.imshow(img, cmap='gray') # Overlay red circle points x_points = [20, 50, 80] y_points = [30, 60, 90] plt.plot(x_points, y_points, 'ro', label='Red points') # Overlay a blue line plt.plot([10, 90], [10, 90], 'b-', label='Blue line') plt.legend() plt.title('Overlaying data on a gray image') plt.show()
OutputSuccess
Important Notes
Make sure the data coordinates match the image size to place points correctly.
You can use different colors and markers to distinguish data on the image.
Use plt.imshow() first, then add data with plt.plot() or plt.scatter().
Summary
Overlaying data on images helps combine pictures with extra information.
Use plt.imshow() to show the image and plt.plot() or plt.scatter() to add data.
Check coordinates so data appears in the right place on the image.