Package: matplotlib-scalebar
matplotlib-scalebarProvides a new artist formatplotlibto display a scale bar, aka micron bar.
It is particularly useful when displaying calibrated images plotted usingplt.imshow(...).The artist supports customization either directly from theScaleBarobject or from the matplotlibrc.InstallationEasiest way to install usingpip:pipinstallmatplotlib-scalebarFor development installation from the git repository:gitclonegit@github.com:ppinard/matplotlib-scalebar.git
pipinstall-ematplotlib-scalebarGetting startedThere are many ways to customize the scale bar.
Examples and explanations of the arguments of theScaleBarclass are givenbelow, but here is a quick start guide.The constructor argumentsdxandunitsspecify the pixel dimension.
For exampleScaleBar(0.2, 'um')indicates that each pixel is equal to 0.2 micrometer.
By default, the scale bar uses SI units of length (e.g. m, cm, um, km, etc.).
See examples below for other system of units.In this example, we load a sample image from the matplotlib library, create a subplot, plot image, create scale bar and add scale bar as an "artist" of the subplot.importnumpyasnpimportmatplotlib.pyplotaspltimportmatplotlib.cbookascbookfrommatplotlib_scalebar.scalebarimportScaleBar# Load imagewithcbook.get_sample_data("s1045.ima.gz")asdfile:im=np.frombuffer(dfile.read(),np.uint16).reshape((256,256))# Create subplotfig,ax=plt.subplots()ax.axis("off")# Plot imageax.imshow(im,cmap="gray")# Create scale barscalebar=ScaleBar(0.08,"cm",length_fraction=0.25)ax.add_artist(scalebar)# Showplt.show()ScaleBar argumentsHere are arguments of theScaleBarclass constructor and examples how to use them.scalebar=ScaleBar(dx,units="m",dimension="si-length",label=None,length_fraction=None,height_fraction=None,width_fraction=None,location=None,pad=None,border_pad=None,sep=None,frameon=None,color=None,box_color=None,box_alpha=None,scale_loc=None,label_loc=None,font_properties=None,label_formatter=None,scale_formatter=None,fixed_value=None,fixed_units=None,animated=False,rotation=None,)Each argument can also be changed afterwards using their respective property.scalebar.dx=2.0The following schematic illustrates the nomenclature used in the definition of the arguments.dx (required)Size of one pixel inunitsspecified by the next argument.Setdxto 1.0 if the axes image has already been calibrated by setting itsextent.fig,ax=plt.subplots()ax.axis("off")ax.imshow(im,cmap="gray",extent=[0,20.48,0,20.48])scalebar=ScaleBar(1,"cm",length_fraction=0.25)ax.add_artist(scalebar)Special notes for geospatial plots:
If you are plotting geospatial coordinates (such as scatterplots of the location of structures,geopandasgeodataframe plots, etc.),dxneeds to be set differently depending on the coordinate system:For UTM based coordinate system, where the X and Y are in meters, simply setdx = 1.For WGS or NAD based coordinate system, where X and Y are in latitude (Y) and longitude (X), compute the distance between two points at the latitude (Y) you wish to have the scale represented and are also one full degree of longitude (X) apart, in meters. For example,dx = great_circle_distance((X, Y), (X + 1, Y))unitsUnits ofdx.
The units needs to be valid for the specifieddimension.
Default:m.dimensionDimension ofdxandunits. It can either be equal:si-length(default): scale bar showing km, m, cm, etc.imperial-length: scale bar showing in, ft, yd, mi, etc.si-length-reciprocal: scale bar showing 1/m, 1/cm, etc.pixel-length: scale bar showing px, kpx, Mpx, etc.angle: scale bar showing °, ʹ (minute of arc) or ʹʹ (second of arc)amatplotlib_scalebar.dimension._Dimensionobjectfig,ax=plt.subplots()ax.axis("off")ax.imshow(im,cmap="gray")scalebar=ScaleBar(0.0315,"in",dimension="imperial-length",length_fraction=0.25)ax.add_artist(scalebar)labelOptional label associated with the scale bar.
Default:None, no label is shown.
The position of the label with respect to the scale bar can be adjusted usinglabel_locargument.length_fractionDesired length of the scale bar as a fraction of the subplot's width.
Default:None, value from matplotlibrc or0.2.
The actual length of the scale bar is automatically determined based on the specified pixel size (dxandunits) and the contraint that the scale value can only take the following numbers: 1, 2, 5, 10, 15, 20, 25, 50, 75, 100, 125, 150, 200, 500 or 750.
If you want a specific value, seefixed_valueandfixed_units.In the example below, the scale bar for alength_fractionof 0.25 and 0.5 is the same because the scale cannot have a value between 2 and 5 mm.height_fractionDeprecated, usewidth_fraction.width_fractionWidth of the scale bar as a fraction of the subplot's height.
Default:None, value from matplotlibrc or0.01.locationA location code, same as matplotlib's legend, either:upper right,upper left,lower left,lower right,right,center left,center right,lower center,upper centerorcenter.
Default:None, value from matplotlibrc orupper right.locAlias forlocation.padPadding inside the box, as a fraction of the font size.
Default:None, value from matplotlibrc or0.2.border_padPadding outside the box, fraction of the font size.
Default:None, value from matplotlibrc or0.1.sepSeparation in points between the scale bar and scale, and between the scale bar and label.
Default:None, value from matplotlibrc or5.frameonWhether to draw a box behind the scale bar, scale and label.
Default:None, value from matplotlibrc orTrue.colorColor for the scale bar, scale and label.
Default:None, value from matplotlibrc ork(black).box_colorBackground color of the box.
Default:None, value from matplotlibrc orw(white).box_alphaTransparency of box.
Default:None, value from matplotlibrc or1.0(opaque).scale_locLocation of the scale with respect to the scale bar.
Eitherbottom,top,left,right,none.
Default:None, value from matplotlibrc orbottom.
If"none", no scale is shown.label_locLocation of the label with respect to the scale bar.
Eitherbottom,top,left,right,none.
Default:None, value from matplotlibrc ortop.
If"none", no label is shown.font_propertiesFont properties of the scale and label text, specified either asdictorstr.
SeeFontPropertiesfor the arguments.
Default:None, default font properties of matplotlib.label_formatterDeprecated, usescale_formatter.scale_formatterCustom function called to format the scale.
Needs to take 2 arguments - the scale value and the unit.
Default:Nonewhich results inscale_formatter=lambdavalue,unit:f"{value}{unit}"fixed_valueValue for the scale.
The length of the scale bar is calculated based on the specified pixel sizedx.
Default:None, the value is automatically determined based onlength_fraction.fixed_unitsUnits of thefixed_value.
Default:None, iffixed valueis notNone, the units ofdxare used.animatedAnimation state.
Default:FalserotationWhether to create a scale bar based on the x-axis (default) or y-axis.rotationcan either behorizontalorvertical.
Note you might have to adjustscale_locandlabel_locto achieve desired layout.
Default:None, value from matplotlibrc orhorizontal.fig,ax=plt.subplots()ax.axis("off")ax.imshow(im,cmap="gray")scalebar=ScaleBar(0.08,"cm",length_fraction=0.25,rotation="vertical",scale_loc="right",border_pad=1,pad=0.5,)ax.add_artist(scalebar)Release notes0.8.1Remove useless shebangs (#47)Correct License trove classifier (#48)0.8.0Fix missing_all_deprecatedin future matplotlib (> 3.5) (#44)Add ability to hide scale and label (#41)0.7.2Fix deprecation warning in matplotlib >= 3.4 ofminimumdescent(#36)0.7.1Fix scalebar location validation from rcParams (#35)0.7.0Add rotation to display scale bar for the y-axis (#30)New documentation (#32)Deprecate argumentheight_fraction, replaced bywidth_fraction(#32)Deprecate argumentlabel_formatter, replaced byscale_formatter(#32)Add aliaslocforlocation(#32)Fix deprecation warning in matplotlib >= 3.3 ofvalidate_legend_loc(#33)0.6.2Fix reciprocal unit (#29)0.6.1Add notes about for geospatial plots (#20)0.6.0Add angular units (#19)Add blit support and fix documentation (#22)Fix issue with getting the wrong preferred values for the scale bar (#23)Package LICENSE file to distribution (#24)0.5.1Remove leftover print statement (#18)0.5.0Add pixel unit (#12)Display micro symbol in text mode (#15)Fix error in length of scale bar; the bar was drawn with an edge around it which made it longer than the actual size (#14)0.4.1Fix deprecated usage of is_string_like (#11)0.4.0Add possibility to specified a fixed value for the scale bar (#9)Contributors@maweigert,@crosbyla,@joschkazj,@AKuederle,@habi,@huangziwei,@SirJohnFranklin,@alexandrejaguar,@parishcm,@wiai,@cosmicshear,@ericore,@seangrogan,@PhilipeRLeal,@din14970,@SarthakJariwala,@k1moradi,@anntzer,@bugalo,@musicinmybrainLicenseLicense under the BSD License, compatible with matplotlib.Copyright (c) 2015-2022 Philippe Pinard