How to use pygmt - 10 common examples

To help you get started, we’ve selected a few pygmt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github GenericMappingTools / pygmt / pygmt / clib / session.py View on Github external
valid : list of str
            A list of valid values for the constant. Will raise a
            :class:`~gmt.exceptions.GMTInvalidInput` exception if the given
            value is not on the list.
        """
        parts = constant.split("|")
        name = parts[0]
        nmodifiers = len(parts) - 1
        if nmodifiers > 1:
            raise GMTInvalidInput(
                "Only one modifier is allowed in constants, {} given: '{}'".format(
                    nmodifiers, constant
                )
            )
        if nmodifiers > 0 and valid_modifiers is None:
            raise GMTInvalidInput(
                "Constant modifiers not allowed since valid values were not "
                + "given: '{}'".format(constant)
            )
        if name not in valid:
            raise GMTInvalidInput(
                "Invalid constant argument '{}'. Must be one of {}.".format(
                    name, str(valid)
                )
            )
        if (
            nmodifiers > 0
            and valid_modifiers is not None
            and parts[1] not in valid_modifiers
        ):
            raise GMTInvalidInput(
                "Invalid constant modifier '{}'. Must be one of {}.".format(
github GenericMappingTools / pygmt / pygmt / _version.py View on Github external
def git_versions_from_keywords(keywords, tag_prefix, verbose):
    """Get version information from git keywords."""
    if not keywords:
        raise NotThisMethod("no keywords at all, weird")
    date = keywords.get("date")
    if date is not None:
        # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
        # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
        # -like" string, which we must then edit to make compliant), because
        # it's been around since git-1.5.3, and it's too difficult to
        # discover which version we're using, or to work around using an
        # older one.
        date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
    refnames = keywords["refnames"].strip()
    if refnames.startswith("$Format"):
        if verbose:
            print("keywords are unexpanded, not using")
        raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
    refs = set([r.strip() for r in refnames.strip("()").split(",")])
    # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
github GenericMappingTools / pygmt / pygmt / _version.py View on Github external
if not keywords:
        raise NotThisMethod("no keywords at all, weird")
    date = keywords.get("date")
    if date is not None:
        # git-2.2.0 added "%cI", which expands to an ISO-8601 -compliant
        # datestamp. However we prefer "%ci" (which expands to an "ISO-8601
        # -like" string, which we must then edit to make compliant), because
        # it's been around since git-1.5.3, and it's too difficult to
        # discover which version we're using, or to work around using an
        # older one.
        date = date.strip().replace(" ", "T", 1).replace(" ", "", 1)
    refnames = keywords["refnames"].strip()
    if refnames.startswith("$Format"):
        if verbose:
            print("keywords are unexpanded, not using")
        raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
    refs = set([r.strip() for r in refnames.strip("()").split(",")])
    # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
    # just "foo-1.0". If we see a "tag: " prefix, prefer those.
    TAG = "tag: "
    tags = set([r[len(TAG) :] for r in refs if r.startswith(TAG)])
    if not tags:
        # Either we're using git < 1.8.3, or there really are no tags. We use
        # a heuristic: assume all version tags have a digit. The old git %d
        # expansion behaves like git log --decorate=short and strips out the
        # refs/heads/ and refs/tags/ prefixes that would let us distinguish
        # between branches and tags. By ignoring refnames without digits, we
        # filter out many common branch names like "release" and
        # "stabilization", as well as "HEAD" and "master".
        tags = set([r for r in refs if re.search(r"\d", r)])
        if verbose:
            print("discarding '%s', no digits" % ",".join(refs - tags))
github GenericMappingTools / pygmt / pygmt / base_plotting.py View on Github external
font color. E.g. "12p,Helvetica-Bold,red" selects a 12p red
            Helvetica-Bold font. If no font info is given then the input
            textfile(s) must have this information in one of its columns.
        justify: str or bool
            Set the alignment which refers to the part of the text string that
            will be mapped onto the (x,y) point. Choose a 2 character
            combination of L, C, R (for left, center, or right) and T, M, B for
            top, middle, or bottom. E.g., BL for lower left. If no
            justification is given then the input textfile(s) must have this as
            a column.
        {J}
        {R}
        """
        kwargs = self._preprocess(**kwargs)

        kind = data_kind(textfiles, x, y, text)
        if kind == "vectors" and text is None:
            raise GMTInvalidInput("Must provide text with x and y.")
        if kind == "file":
            for textfile in textfiles.split(" "):  # ensure that textfile(s) exist
                if not os.path.exists(textfile):
                    raise GMTInvalidInput(f"Cannot find the file: {textfile}")

        if angle is not None or font is not None or justify is not None:
            if "F" not in kwargs.keys():
                kwargs.update({"F": ""})
            if angle is not None and isinstance(angle, (int, float)):
                kwargs["F"] += f"+a{str(angle)}"
            if font is not None and isinstance(font, str):
                kwargs["F"] += f"+f{font}"
            if justify is not None and isinstance(justify, str):
                kwargs["F"] += f"+j{justify}"
github GenericMappingTools / pygmt / pygmt / base_plotting.py View on Github external
if kind == "file":
            for textfile in textfiles.split(" "):  # ensure that textfile(s) exist
                if not os.path.exists(textfile):
                    raise GMTInvalidInput(f"Cannot find the file: {textfile}")

        if angle is not None or font is not None or justify is not None:
            if "F" not in kwargs.keys():
                kwargs.update({"F": ""})
            if angle is not None and isinstance(angle, (int, float)):
                kwargs["F"] += f"+a{str(angle)}"
            if font is not None and isinstance(font, str):
                kwargs["F"] += f"+f{font}"
            if justify is not None and isinstance(justify, str):
                kwargs["F"] += f"+j{justify}"

        with GMTTempFile(suffix=".txt") as tmpfile:
            with Session() as lib:
                if kind == "file":
                    fname = textfiles
                elif kind == "vectors":
                    pd.DataFrame.from_dict(
                        {
                            "x": np.atleast_1d(x),
                            "y": np.atleast_1d(y),
                            "text": np.atleast_1d(text),
                        }
                    ).to_csv(
                        tmpfile.name,
                        sep="\t",
                        header=False,
                        index=False,
                        quoting=csv.QUOTE_NONE,
github GenericMappingTools / pygmt / doc / conf.py View on Github external
"image_scrapers": (PyGMTScraper(),),
}

# Sphinx project configuration
templates_path = ["_templates"]
exclude_patterns = ["_build", "**.ipynb_checkpoints"]
source_suffix = ".rst"
# The encoding of source files.
source_encoding = "utf-8-sig"
master_doc = "index"

# General information about the project
year = datetime.date.today().year
project = "PyGMT"
copyright = "2017-{}, The PyGMT Developers.".format(year)
if len(__version__.split("+")) > 1 or __version__ == "unknown":
    version = "dev"
else:
    version = __version__

# These enable substitutions using |variable| in the rst files
rst_epilog = """
.. |year| replace:: {year}
""".format(
    year=year
)

html_last_updated_fmt = "%b %d, %Y"
html_title = "PyGMT"
html_short_title = "PyGMT"
html_logo = ""
html_favicon = "_static/favicon.png"
github GenericMappingTools / pygmt / dev / _downloads / 29ea8d0bf6fbe57cd57e12a636ee5dfc / azim_lambert.py View on Github external
"""
Lambert Azimuthal Equal Area
============================

``Alon0/lat0[/horizon]/width``: ``lon0`` and ``lat0`` specifies the projection center.
``horizon`` specifies the max distance from projection center (in degrees, <= 180,
default 90).
"""
import pygmt

fig = pygmt.Figure()
fig.coast(region="g", frame="afg", land="gray", projection="A30/-20/60/8i")
fig.show()
github GenericMappingTools / pygmt / dev / _downloads / 85bd7795caf2775b21629621fe089c88 / cyl_mercator.py View on Github external
"""
Mercator
========

``M[lon0/][lat0/]width``: Give central meridian ``lon0`` (optional) and
standard parallel ``lat0`` (optional).
"""
import pygmt

fig = pygmt.Figure()
fig.coast(region=[0, 360, -80, 80], frame="afg", land="gray", projection="M0/0/8i")
fig.show()
github GenericMappingTools / pygmt / examples / projections / cyl / cyl_cassini.py View on Github external
"""
Cassini Cylindrical
============================

``Clon0/lat0/width``: ``lon0`` and ``lat0`` specifies the projection center.
"""
import pygmt

fig = pygmt.Figure()
# Use the ISO code for Madagascar (MG) and pad it by 2 degrees (+R2)
fig.coast(projection="C47/-19/8i", region="MG+R2", frame="afg", land="gray", borders=1)
fig.show()
github GenericMappingTools / pygmt / dev / _downloads / 804933c00171bd80c8cb60638d8f2bc2 / coastlines.py View on Github external
########################################################################################
# Resolutions
# -----------
#
# The coastline database comes with 5 resolutions. The resolution drops by 80% between
# levels:
#
# 1. ``"c"``: crude
# 2. ``"l"``: low (default)
# 3. ``"i"``: intermediate
# 4. ``"h"``: high
# 5. ``"f"``: full

oahu = [-158.3, -157.6, 21.2, 21.8]
fig = pygmt.Figure()
for res in ["c", "l", "i", "h", "f"]:
    fig.coast(resolution=res, shorelines="1p", region=oahu, projection="M5i")
    fig.shift_origin(xshift="5i")
fig.show()

########################################################################################
# Land and water
# --------------
#
# Use the ``land`` and ``water`` attributes to specify a fill color for land and water
# bodies. The colors can be given by name or hex codes (like the ones used in HTML and
# CSS):

fig = pygmt.Figure()
fig.basemap(region="g", projection="W10i", frame=True)
fig.coast(land="#666666", water="skyblue")