How to insert a scale bar in a map in Matplotlib?

To insert a scale bar in a map in matplotlib, we can use AnchoredSizeBar() class to instantiate the scalebar object. This is particularly useful for geographic visualizations where you need to show distance measurements.

Steps

  • Set the figure size and adjust the padding between and around the subplots.

  • Create random data using numpy.

  • Use imshow() method to display data as an image, i.e., on a 2D regular raster.

  • Get the current axis using gca() method.

  • Draw a horizontal scale bar with a center-aligned label underneath.

  • Add a scalebar artist to the current axis.

  • Turn off the axes.

  • To display the figure, use show() method.

Example

from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = np.random.rand(5, 5)

img = plt.imshow(data, cmap="YlGnBu")
ax = plt.gca()
scalebar = AnchoredSizeBar(ax.transData, 1, "1 Meter", 9)

ax.add_artist(scalebar)
ax.axis('off')
plt.show()

Output

A map visualization with a scale bar showing "1 Meter" positioned at the bottom-right corner.

Understanding AnchoredSizeBar Parameters

The AnchoredSizeBar constructor takes the following key parameters ?

  • transform: The coordinate system (usually ax.transData)

  • size: The length of the scale bar in data coordinates

  • label: Text label for the scale bar

  • loc: Position (9 = bottom-right, 2 = upper-left, etc.)

Advanced Example with Custom Styling

from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
import numpy as np

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

# Create sample geographic-like data
data = np.random.rand(10, 10) * 100

img = plt.imshow(data, cmap="terrain", extent=[0, 10, 0, 10])
ax = plt.gca()

# Create custom scale bar
scalebar = AnchoredSizeBar(
    ax.transData, 
    2, 
    "2 km", 
    loc=4,  # lower-right
    pad=0.5, 
    color='white',
    frameon=True,
    size_vertical=0.2
)

ax.add_artist(scalebar)
plt.title("Geographic Map with Scale Bar")
plt.xlabel("Distance (km)")
plt.ylabel("Distance (km)")
plt.show()

Conclusion

The AnchoredSizeBar class provides an easy way to add scale bars to matplotlib maps. Use appropriate size values in your data coordinates and choose suitable positioning with the loc parameter for clear visualization.

Updated on: 2026-03-25T21:54:55+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements