There is already an existing class for scales in matplotlib called AnchoredSizeBar . In the example below, AnchoredSizeBar is used to add a scale to the image (or display a random area of โโ100x100 meters).
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar import matplotlib.font_manager as fm fontprops = fm.FontProperties(size=18) fig, ax = plt.subplots() ax.imshow(np.random.random((10,10)),extent=[0,100,0,100])
The extent defines the max and min images of horizontal and vertical values.
scalebar = AnchoredSizeBar(ax.transData, 20, '20 m', 'lower center', pad=0.1, color='white', frameon=False, size_vertical=1, fontproperties=fontprops) ax.add_artist(scalebar)
The four first arguments to AnchoredSizeBar are the coordinate system transformation object, scale length, label, and location. Additional optional arguments change the layout. They are well explained in docstring.
ax.set_yticks([]) ax.set_xticks([])
This gives a Scalebar on an image / map at a random distance of 100x100 meters
idahj
source share