draw grid lines over an image in matplotlib

Learn draw grid lines over an image in matplotlib with practical examples, diagrams, and best practices. Covers matplotlib, matplotlib-basemap development techniques with visual explanations.

Overlaying Grid Lines on Images in Matplotlib

Hero image for draw grid lines over an image in matplotlib

Learn how to effectively draw customizable grid lines over an image using Matplotlib, including handling coordinate systems and Basemap projections.

Drawing grid lines over an image in Matplotlib is a common requirement for data visualization, especially when working with geographical data, scientific plots, or any scenario where precise spatial referencing is needed. This article will guide you through the process, covering basic image overlays, handling different coordinate systems, and integrating with Matplotlib Basemap for geographical projections.

Basic Grid Overlay on a Static Image

The simplest way to draw a grid over an image is to load the image using plt.imshow() and then enable the grid using plt.grid(True). However, for more control over the grid lines (e.g., spacing, color, style), you'll need to manually set the major and minor ticks and then draw the grid. This approach works well for images where the axes directly correspond to pixel coordinates or a simple Cartesian system.

import matplotlib.pyplot as plt
import numpy as np

# Create a dummy image (replace with your actual image loading)
img = np.random.rand(100, 150)

fig, ax = plt.subplots(figsize=(8, 6))
ax.imshow(img, cmap='gray', origin='upper')

# Set major ticks
ax.set_xticks(np.arange(0, img.shape[1], 25))
ax.set_yticks(np.arange(0, img.shape[0], 20))

# Set minor ticks
ax.set_xticks(np.arange(0.5, img.shape[1], 5), minor=True)
ax.set_yticks(np.arange(0.5, img.shape[0], 5), minor=True)

# Draw grid lines
ax.grid(which='major', color='red', linestyle='-', linewidth=1)
ax.grid(which='minor', color='gray', linestyle=':', linewidth=0.5)

ax.set_title('Grid Overlay on a Static Image')
plt.xlabel('X-axis (pixels)')
plt.ylabel('Y-axis (pixels)')
plt.show()

Python code to draw a customizable grid over a static image using Matplotlib.

Grids with Matplotlib Basemap for Geographical Data

For geographical images, especially those projected onto a map, Matplotlib's Basemap toolkit (while deprecated, still widely used) provides specialized functions for drawing meridians and parallels. This is crucial for accurately representing latitude and longitude grids over satellite imagery or geographical maps. The process involves initializing a Basemap instance with the desired projection and then using its drawparallels and drawmeridians methods.

graph TD
    A[Start] --> B{Load Image/Data}
    B --> C[Initialize Basemap Instance]
    C --> D[Plot Image with Basemap.imshow()]
    D --> E[Draw Parallels (Latitudes)]
    E --> F[Draw Meridians (Longitudes)]
    F --> G[Customize Grid Labels/Styles]
    G --> H[Show Plot]
    H --> I[End]

Workflow for drawing geographical grids using Matplotlib Basemap.

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np

# Dummy image data (e.g., a satellite image)
# In a real scenario, this would be loaded from a file
img_data = np.random.rand(500, 500)

# Define map boundaries (example for a region)
llcrnrlon = -120  # Lower-left corner longitude
llcrnrlat = 30    # Lower-left corner latitude
urcrnrlon = -70   # Upper-right corner longitude
urcrnrlat = 50    # Upper-right corner latitude

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111)

# Create a Basemap instance
m = Basemap(projection='merc',
            llcrnrlon=llcrnrlon, llcrnrlat=llcrnrlat,
            urcrnrlon=urcrnrlon, urcrnrlat=urcrnrlat,
            resolution='l', ax=ax)

# Plot the image using Basemap's imshow
# Ensure the extent matches your geographical coordinates
m.imshow(img_data, origin='upper', extent=[llcrnrlon, urcrnrlon, llcrnrlat, urcrnrlat], cmap='viridis')

# Draw parallels (latitude lines)
parallels = np.arange(30., 51., 5.)
m.drawparallels(parallels, labels=[1,0,0,0], fontsize=10, linewidth=0.75, color='white')

# Draw meridians (longitude lines)
meridians = np.arange(-120., -69., 10.)
m.drawmeridians(meridians, labels=[0,0,0,1], fontsize=10, linewidth=0.75, color='white')

ax.set_title('Geographical Grid Overlay with Basemap')
plt.show()

Example of drawing latitude and longitude grids over an image using Matplotlib Basemap.

Customizing Grid Appearance and Labels

Beyond basic lines, Matplotlib offers extensive customization options for grid appearance. You can control line style, color, width, and even add labels to your grid lines. For non-geographical plots, you can use ax.tick_params() to style the ticks and labels, and ax.grid() for the lines themselves. For Basemap, the drawparallels and drawmeridians methods have parameters like labels, fontsize, color, and dashes to achieve the desired look.

import matplotlib.pyplot as plt
import numpy as np

img = np.random.rand(100, 150)

fig, ax = plt.subplots(figsize=(8, 6))
ax.imshow(img, cmap='plasma', origin='upper', extent=[0, 15, 0, 10]) # Example with custom extent

# Set custom tick locations and labels
major_xticks = np.arange(0, 16, 3)
major_yticks = np.arange(0, 11, 2)

ax.set_xticks(major_xticks)
ax.set_yticks(major_yticks)

# Customize major grid lines
ax.grid(which='major', color='cyan', linestyle='--', linewidth=1.5, alpha=0.7)

# Customize tick parameters (labels)
ax.tick_params(axis='x', colors='blue', labelsize=12, rotation=45)
ax.tick_params(axis='y', colors='green', labelsize=12)

ax.set_title('Customized Grid and Labels')
plt.xlabel('Custom X-Units')
plt.ylabel('Custom Y-Units')
plt.show()

Advanced customization of grid lines and labels in Matplotlib.