GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Add Figure.scalebar to plot a scale bar on maps by seisman · Pull Request #4015 · GenericMappingTools/pygmt

Add Figure.scalebar to plot a scale bar on maps #4015

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
seisman merged 21 commits into main from feature/scalebar
Jan 21, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

Add Figure.scalebar to plot a scale bar on maps #4015

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
b585969
Add Figure.scalebar to plot a scale bar on maps
seisman Jul 26, 2025
dc74f82
Fix typos
seisman Dec 20, 2025
3c56bca
Fix tyops
seisman Dec 20, 2025
2bb298b
Rename parameter scale_position to scale_at
seisman Dec 27, 2025
5a31c6c
Update pygmt/src/scalebar.py
seisman Dec 29, 2025
78a9307
Length is a required parameter
seisman Jan 11, 2026
7988be1
Need to pass kwdict
seisman Jan 11, 2026
2a190b3
Merge branch 'main' into feature/scalebar
seisman Jan 12, 2026
1c53522
Fix a typo [skip ci]
seisman Jan 12, 2026
677e0b9
Merge branch 'main' into feature/scalebar
seisman Jan 17, 2026
c192853
Update pygmt/src/scalebar.py
seisman Jan 17, 2026
777cd3a
Fix docstrings
seisman Jan 17, 2026
188367a
Improve docstrings for fancy
seisman Jan 17, 2026
c7b86c9
Apply suggestions from code review
seisman Jan 17, 2026
cc15a31
Update pygmt/src/scalebar.py
seisman Jan 18, 2026
1c8c5c1
Merge branch 'main' into feature/scalebar
seisman Jan 18, 2026
f44f784
Merge branch 'main' into feature/scalebar
seisman Jan 19, 2026
971d147
Simplify _parse_position
seisman Jan 19, 2026
e2c1254
Merge branch 'main' into feature/scalebar
seisman Jan 19, 2026
0561ba4
Rename scale_at to scale_loc
seisman Jan 20, 2026
cc40c8f
Update pygmt/src/scalebar.py
seisman Jan 21, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

1 change: 1 addition & 0 deletions 1 doc/api/index.rst
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Plotting map elements
Figure.inset
Figure.legend
Figure.logo
Figure.scalebar
Figure.solar
Figure.text
Figure.timestamp
Expand Down
1 change: 1 addition & 0 deletions 1 pygmt/figure.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,7 @@ def _repr_html_(self) -> str:
plot3d,
psconvert,
rose,
scalebar,
set_panel,
shift_origin,
solar,
Expand Down
1 change: 1 addition & 0 deletions 1 pygmt/src/__init__.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
from pygmt.src.project import project
from pygmt.src.psconvert import psconvert
from pygmt.src.rose import rose
from pygmt.src.scalebar import scalebar
from pygmt.src.select import select
from pygmt.src.shift_origin import shift_origin
from pygmt.src.solar import solar
Expand Down
146 changes: 146 additions & 0 deletions 146 pygmt/src/scalebar.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"""
scalebar - Add a scale bar.
"""

from collections.abc import Sequence
from typing import Literal

from pygmt._typing import AnchorCode
from pygmt.alias import Alias, AliasSystem
from pygmt.clib import Session
from pygmt.helpers import build_arg_list, fmt_docstring
from pygmt.params import Box, Position
from pygmt.src._common import _parse_position

__doctest_skip__ = ["scalebar"]


@fmt_docstring
def scalebar( # noqa: PLR0913
self,
length: float | str,
height: float | str | None = None,
position: Position | Sequence[float | str] | AnchorCode | None = None,
scale_loc: float | Sequence[float] | bool = False,
label: str | bool = False,
label_alignment: Literal["left", "right", "top", "bottom"] | None = None,
Comment thread

@seisman seisman Dec 11, 2025

Copy link
Copy Markdown
Member Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GMT and GMT.jl use align, currently PyGMT uses label_alignment, but maybe label_position?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@yvonnefroehlich yvonnefroehlich Jan 20, 2026

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel label_position is more consisten, as we have nan_position for Figure.colorbar. And it is a bit shorter.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
unit: bool = False,
Comment thread
seisman marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

fancy: bool = False,
vertical: bool = False,
box: Box | bool = False,
verbose: Literal["quiet", "error", "warning", "timing", "info", "compat", "debug"]
| bool = False,
panel: int | Sequence[int] | bool = False,
perspective: float | Sequence[float] | str | bool = False,
transparency: float | None = None,
):
"""
Add a scale bar on the plot.

Comment thread
seisman marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

Parameters
----------
length
Length of the scale bar in kilometers. Append a suffix to specify another unit.
Valid units are: **e**: meters; **f**: feet; **k**: kilometers; **M**: statute
miles; **n**: nautical miles; **u**: US survey feet.
height
Height of the scale bar [Default is ``"5p"``]. Only works when ``fancy=True``.
position
Position of the scale bar on the plot. It can be specified in multiple ways:

- A :class:`pygmt.params.Position` object to fully control the reference point,
anchor point, and offset.
- A sequence of two values representing the x- and y-coordinates in plot
coordinates, e.g., ``(1, 2)`` or ``("1c", "2c")``.
- A :doc:`2-character justification code </techref/justification_codes>` for a
position inside the plot, e.g., ``"TL"`` for Top Left corner inside the plot.

If not specified, defaults to the Bottom Left corner of the plot with a 0.2-cm
and 0.4-cm offset in the x- and y-directions, respectively.
scale_loc
Specify the location where the map scale is calculated. It can be:

- *slat*: Map scale is calculated for latitude *slat*.
- (*slon*, *slat*): Map scale is calculated for latitude *slat* and longitude
*slon*, which is useful for oblique projections.
- ``True``: Map scale is calculated for the middle of the map.
- ``False``: Default to the location of the reference point.
label
Text string for the scale bar label. If ``False``, no label is added. If
``True``, the distance unit provided in the ``length`` parameter is used
[Default is ``"km"``]. Requires ``fancy=True``.
label_alignment
Alignment of the scale bar label. Choose from ``"left"``, ``"right"``,
``"top"``, or ``"bottom"`` [Default is ``"top"``].
fancy
If ``True``, draw a "fancy" scale bar, which is a segmented bar with alternating
black and white rectangles. If ``False``, draw a plain scale bar. Only supported
for non-Cartesian projections.
unit
If ``True``, append the unit to all distance annotations along the scale. For a
plain scale, this will instead select the unit to be appended to the distance
length. The unit is determined from the suffix provided to the ``length``
parameter or defaults to ``"km"``.
vertical
If ``True``, plot a vertical rather than a horizontal scale. Only
supported for Cartesian projections.
box
Draw a background box behind the scale bar. If set to ``True``, a simple
rectangular box is drawn using :gmt-term:`MAP_FRAME_PEN`. To customize the box
appearance, pass a :class:`pygmt.params.Box` object to control style, fill, pen,
and other box properties.
$verbose
$panel
$perspective
$transparency

Examples
--------
>>> import pygmt
>>> from pygmt.params import Position
>>> fig = pygmt.Figure()
>>> fig.basemap(region=[0, 80, -30, 30], projection="M10c", frame=True)
>>> fig.scalebar(
... length=1000,
... position=Position((10, 10), cstype="mapcoords"),
... fancy=True,
... label="Scale",
... unit=True,
... )
>>> fig.show()
"""
self._activate_figure()
position = _parse_position(position, default=Position("BL", offset=(0.2, 0.4)))

aliasdict = AliasSystem(
F=Alias(box, name="box"),
L=[
Alias(position, name="position"),
Alias(length, name="length", prefix="+w"),
Alias(
label_alignment,
name="label_alignment",
prefix="+a",
mapping={"left": "l", "right": "r", "top": "t", "bottom": "b"},
),
Alias(scale_loc, name="scale_loc", prefix="+c", sep="/", size=2),
Alias(fancy, name="fancy", prefix="+f"),
Alias(label, name="label", prefix="+l"),
Alias(unit, name="unit", prefix="+u"),
Alias(vertical, name="vertical", prefix="+v"),
],
).add_common(
V=verbose,
c=panel,
p=perspective,
t=transparency,
)

confdict = {}
if height is not None:
confdict["MAP_SCALE_HEIGHT"] = height

with Session() as lib:
lib.call_module(
module="basemap", args=build_arg_list(aliasdict, confdict=confdict)
)
5 changes: 5 additions & 0 deletions 5 pygmt/tests/baseline/test_scalebar.png.dvc
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
outs:
- md5: ad7658ed25f1a9f0a1ba74a0ffa84a4b
size: 10207
hash: md5
path: test_scalebar.png
5 changes: 5 additions & 0 deletions 5 pygmt/tests/baseline/test_scalebar_cartesian.png.dvc
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
outs:
- md5: e09a7c67f6146530ea594694853b6f98
size: 6508
hash: md5
path: test_scalebar_cartesian.png
5 changes: 5 additions & 0 deletions 5 pygmt/tests/baseline/test_scalebar_complete.png.dvc
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
outs:
- md5: c018b219d3ebc719fb1b1686e074dcd9
size: 11749
hash: md5
path: test_scalebar_complete.png
51 changes: 51 additions & 0 deletions 51 pygmt/tests/test_scalebar.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
Test Figure.scalebar.
"""

import pytest
from pygmt import Figure
from pygmt.params import Position


@pytest.mark.mpl_image_compare
def test_scalebar():
"""
Create a map with a scale bar.
"""
fig = Figure()
fig.basemap(region=[100, 120, 20, 30], projection="M10c", frame=True)
fig.scalebar(length=500)
return fig


@pytest.mark.mpl_image_compare
def test_scalebar_complete():
"""
Test all parameters of scalebar.
"""
fig = Figure()
fig.basemap(region=[100, 120, 20, 30], projection="M10c", frame=True)
fig.scalebar(
length=1000,
height="10p",
position=Position((110, 22), cstype="mapcoords"),
fancy=True,
label="Scale",
label_alignment="left",
scale_loc=(110, 25),
unit=True,
box=True,
)
return fig


@pytest.mark.mpl_image_compare
def test_scalebar_cartesian():
"""
Test scale bar in Cartesian coordinates.
"""
fig = Figure()
fig.basemap(region=[0, 10, 0, 5], projection="X10c/5c", frame=True)
fig.scalebar(length=1, position=Position((2, 1), cstype="mapcoords"))
fig.scalebar(length=1, position=Position((4, 1), cstype="mapcoords"), vertical=True)
return fig
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.