ternary_diagram package#

class ternary_diagram.TernaryDiagram(materials: tuple[str, str, str], ax: Axes | None = None, auto_latex_notation: bool = True, *, tight_layout: bool | None = None, border_kw: Mapping[str, Any] | None = None, grid_kw: Mapping[str, Any] | None = None, tick_kw: Mapping[str, Any] | None = None, axis_label_kw: Mapping[str, Any] | None = None, vertex_label_kw: Mapping[str, Any] | None = None)#

Bases: object

Ternary diagram drawn on a matplotlib Axes.

A ternary diagram shows compositions of three components (the materials) as points in a triangle whose vertices are the pure materials, given in the order top, bottom left, bottom right (counterclockwise from the top vertex). The diagram draws on one matplotlib Axes, the ax given at construction or the current Axes, so it can be one panel of a figure made with plt.subplots. At construction, it sets the aspect of the Axes to equal, hides the ticks and the spines of the Axes and draws the skeleton of the diagram. The aspect is kept by widening the data limits (adjustable="datalim"); from ternary-diagram 4.0.0, the box of the Axes is shrunk to the triangle instead (adjustable="box"), which can move legends placed with loc and, on a figure with a layout engine, shorten the colorbars added automatically. Call td.ax.set_aspect("equal", adjustable="box") after construction to try it now.

The plotting methods draw on the Axes of the diagram and return the matplotlib objects that they create. Those that take compositions (vector) read each row as the amounts of the three materials in the order of materials and normalize it, so the sum does not have to be 1:

  • scatter(): points, optionally colored by a value z.

  • contour(): filled or line contours of a value z given at scattered compositions.

  • tripcolor(): the triangles between scattered compositions, colored by a value z without interpolation.

  • heatmapf(): a heat map of a function f(a, b, c) of the composition, evaluated on a regular triangular lattice.

  • plot(): lines that join compositions, such as tie lines.

  • fill(): a polygon of compositions, such as a phase region.

  • text(): a text centered at a composition.

  • annotate(): a note at a composition, slightly to its upper right by default.

  • colorbar(): a colorbar of a plot colored by a value.

The skeleton is drawn in 5 parts: the border of the triangle, the grid, the tick labels, the axis titles (none by default) and the vertex labels (the materials). The look of each part can be given at construction with its *_kw argument and changed afterwards with its change method, and the artists that it draws are returned by its read-only accessor:

At construction

After construction

Artists

border_kw

set_border()

border_lines_

grid_kw

set_grid()

grid_lines_

tick_kw

set_ticks()

tick_labels_

axis_label_kw

set_axis_labels()

axis_labels_

vertex_label_kw

set_vertex_labels()

vertex_labels_

Draw the skeleton of a ternary diagram on an Axes.

Parameters:
  • materials (sequence of str) – Names of the three components as a list or a tuple, shown at the vertices of the triangle in the order top, bottom left, bottom right (counterclockwise from the top vertex). The columns of the compositions given to the plotting methods follow this order. If more than 3 items are given, only the first 3 are used; fewer than 3 raise a ValueError. With auto_latex_notation=True, each item must be a str.

  • ax (matplotlib.axes.Axes, optional) – Axes to draw the diagram on. If None, the current Axes (plt.gca()) is used, which creates a figure and an Axes if there are none. Anything other than an Axes or None raises a TypeError. Pass it by keyword: passing it by position is deprecated since 3.4.0 and emits a FutureWarning, and it will be keyword-only in ternary-diagram 4.0.0, by default None

  • auto_latex_notation (bool, optional) – Whether to write the numbers in the vertex labels as subscripts in LaTeX notation ("Li2O" to "Li$_{2}$O"). False shows materials as they are. The setting is fixed at construction and also applies to the vertex labels given later with set_vertex_labels(). It is also the setting that text() follows by default and, from ternary-diagram 4.0.0, annotate() and the annotations of scatter(); see those methods for their rules. Pass it by keyword: passing it by position is deprecated since 3.4.0 and emits a FutureWarning, and it will be keyword-only in ternary-diagram 4.0.0, by default True

  • tight_layout (bool or None, optional) – Whether to adjust the figure margins with Figure.tight_layout() after each plotting call. True adjusts them, and False leaves the layout untouched. None keeps the v3.x behavior: the margins are adjusted and a FutureWarning is emitted once per diagram. The default will change to tight_layout=False in ternary-diagram 4.0.0. Figures with a layout engine (e.g. layout="constrained") and subfigures are never adjusted, whatever the value, by default None

  • border_kw (dict or None, optional) – Settings of the border of the triangle. Passing border_kw is equivalent to calling set_border(**border_kw) right after construction; see set_border() for the accepted keys. None draws the border with the default appearance, by default None

  • grid_kw (dict or None, optional) – Settings of the grid. Passing grid_kw is equivalent to calling set_grid(**grid_kw) right after construction; see set_grid() for the accepted keys. None draws the grid with the default appearance, by default None

  • tick_kw (dict or None, optional) – Settings of the tick labels. Passing tick_kw is equivalent to calling set_ticks(**tick_kw) right after construction; see set_ticks() for the accepted keys. None draws the tick labels with the default appearance, by default None

  • axis_label_kw (dict or None, optional) – Settings of the axis titles along the edges. Passing axis_label_kw is equivalent to calling set_axis_labels(**axis_label_kw) right after construction; see set_axis_labels() for the accepted keys, such as labels for the titles. None uses the default appearance, which draws no titles, by default None

  • vertex_label_kw (dict or None, optional) – Settings of the vertex labels. Passing vertex_label_kw is equivalent to calling set_vertex_labels(**vertex_label_kw) right after construction; see set_vertex_labels() for the accepted keys, except labels: the labels are given by materials, and labels here raises a ValueError. None draws the vertex labels with the default appearance, by default None

x_#

The x coordinates of the points drawn by the plotting methods, keyed by the name of the method (such as "scatter"). Each value is a list with one 1-D array per call, in the order of the calls. The coordinates are those of the Axes, where the bottom left vertex is (0, 0), the bottom right vertex is (1, 0) and the top vertex is (0.5, sqrt(3)/2). It is a collections.defaultdict, so a method not called yet gives an empty list.

Type:

dict of str to list of numpy.ndarray

y_#

The y coordinates of the points drawn by the plotting methods, in the same form as x_.

Type:

dict of str to list of numpy.ndarray

Notes

The materials are given counterclockwise from the top vertex. The ticks of each material are on one edge, and along that edge its value increases counterclockwise, from 0 to 1 at the vertex of the material (0 to 100 with the default format):

  • The 1st material (top vertex): on the right edge, increasing from the bottom right vertex to the top vertex.

  • The 2nd material (bottom left vertex): on the left edge, increasing from the top vertex to the bottom left vertex.

  • The 3rd material (bottom right vertex): on the bottom edge, increasing from the bottom left vertex to the bottom right vertex.

The grid line of a value starts at that value on the tick edge of the material and runs parallel to the edge opposite to the vertex of the material: the points on it have that value. With endpoints=True (see set_ticks()), the labels of the values 0 and 1 are also drawn, and the label of 1 of the 2nd material and that of 0 of the 3rd material come close to each other at the bottom left vertex.

A change method removes all the artists that its part drew before and draws new ones. The other parts, the artists drawn by the user (scatter points, contours, lines, annotations, …) and the position and size of the Axes are not changed. Settings not given keep their previous values: a named item (such as step) given as None, and a matplotlib property left out. A part hidden with visible=False keeps its settings and is drawn with them again with visible=True. If a change raises an error, the part keeps its previous settings and artists. Artists of a part that are no longer on the Axes, because they were removed with Artist.remove or the Axes was cleared, are left as they are by the change methods.

The matplotlib properties given to a part apply to all its artists and override the defaults of the part, including those that differ by edge or by vertex (the rotation and the alignments of the labels). Once such a property is given, the defaults of the edges or the vertices cannot be restored. The *_kw arguments and the change methods take only the named items of the part and the properties of its artists (matplotlib.lines.Line2D or matplotlib.text.Text), not the other arguments of Axes.plot and Axes.text, such as scalex or fontdict: pass the items of a fontdict as keywords (**fontdict).

A redrawn part keeps its zorder unless zorder is given: 1 for the border and the grid, and the default of matplotlib for the labels (3 for text). With the same zorder, the border is always drawn over the grid. Among artists with the same zorder, the one added to the Axes later is drawn on top, so a redrawn part is drawn over the artists with the same zorder that were drawn before the change: for example, the labels over scatter points (zorder 3 by default) and, after a change of the grid, the grid and the border over lines drawn with zorder=1. Give zorder to the change method or to your own artists to choose the order.

Examples

Draw a diagram on an Axes. The numbers in the materials are shown as subscripts, and the coordinates of the plotted points are recorded by the name of the method.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> [label.get_text() for label in td.vertex_labels_]
['Li$_{2}$O', 'La$_{2}$O$_{3}$', 'TiO$_{2}$']
>>> points = td.scatter([[1, 1, 1], [1, 2, 3]])
>>> len(td.x_["scatter"])
1

Show the materials as they are, such as names that are not chemical formulas.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(
...     ["Solvent A", "Solvent B", "Polymer 1"],
...     ax=ax,
...     auto_latex_notation=False,
... )
>>> [label.get_text() for label in td.vertex_labels_]
['Solvent A', 'Solvent B', 'Polymer 1']
annotate(text: str, vector: ArrayLike, *, auto_latex_notation: bool | None = None, **kwargs) → Annotation#

Annotate a composition with a text.

The text is placed slightly to the upper right of the point of the composition by default. This is a wrapper of matplotlib.pyplot.annotate.

See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.annotate.html

Parameters:
  • text (str) – Text of the note. A str is formatted as described in auto_latex_notation: by default, a chemical formula such as "Li2O" is shown as "Li$_{2}$O", and a text containing $ (mathtext) is shown as it is. Objects other than str, such as numbers, are shown as text without formatting.

  • vector (array-like of shape (3,)) – Composition to annotate: the amounts of the three components in the same order as materials (top, bottom-left, bottom-right; counterclockwise from the top vertex). It is normalized, so the sum does not have to be 1. Any array-like with exactly three elements, such as one of shape (1, 3), is accepted; other lengths raise a ValueError.

  • auto_latex_notation (bool or None, optional) – Whether to write the chemical formulas in text in LaTeX notation ("Li2O" to "Li$_{2}$O"). True formats each word that looks like a chemical formula (see ternary_diagram.utils.to_latex_notation()) and keeps the other words, and False shows the text as it is. None keeps the v3.x behavior: every number in a str is written as a subscript ("Sample 1" to "Sample $_{1}$"), except in a text containing $, and a FutureWarning is emitted once per diagram when the display will change. In ternary-diagram 4.0.0, None will follow auto_latex_notation of TernaryDiagram, by default None

  • **kwargs – Other arguments of matplotlib.pyplot.annotate, such as xytext, fontsize, color or arrowprops, passed to matplotlib as they are. They take precedence over the defaults of this method: xytext is 0.02 to the right of and 0.02 above the point in the data coordinates of the diagram (whose edges have length 1), and fontsize is 8. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.annotate.html

Returns:

The note, as returned by matplotlib.axes.Axes.annotate. Its xy is the point of the composition.

Return type:

matplotlib.text.Annotation

See also

text

A text centered at a composition.

scatter

Points at compositions, with a text next to each with annotations.

Examples

Annotate a composition with a chemical formula, which is written with subscripts.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> note = td.annotate("Li2O", [2, 1, 1])
>>> note.get_text()
'Li$_{2}$O'

Place a plain text away from the composition with an arrow that points to it. auto_latex_notation=True keeps the number in the text as it is.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> note = td.annotate(
...     "Sample 1",
...     [1, 2, 3],
...     xytext=(0.7, 0.6),
...     arrowprops={"arrowstyle": "->"},
...     auto_latex_notation=True,
... )
>>> note.get_text()
'Sample 1'
property ax: Axes#

Axes that the diagram is drawn on.

It is the ax given at construction, or the current Axes if ax was None. It is read-only: assigning to it raises an AttributeError.

Returns:

The Axes of the diagram.

Return type:

matplotlib.axes.Axes

property axis_labels_: list[Text]#

Axis titles drawn now.

Use them to adjust a single title. Each access returns a new list. set_axis_labels() replaces the titles with new ones, which drops the changes made to them directly. To hide the titles, use set_axis_labels(visible=False) rather than removing them.

Returns:

A new list of the drawn axis titles in the order of the materials, without the materials that have no title, empty while the axis titles are hidden. No titles are drawn by default.

Return type:

list of matplotlib.text.Text

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> td.axis_labels_  # no titles by default
[]
>>> _ = td.set_axis_labels([None, None, "TiO2 / mol%"])
>>> [title.get_text() for title in td.axis_labels_]
['TiO2 / mol%']
property border_lines_: list[Line2D]#

Lines of the border drawn now.

Use them to adjust a single edge. Each access returns a new list. set_border() replaces the lines with new ones, which drops the changes made to them directly. To hide the border, use set_border(visible=False) rather than removing the lines.

Returns:

A new list of the bottom, left and right edges, empty while the border is hidden.

Return type:

list of matplotlib.lines.Line2D

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> bottom, left, right = td.border_lines_
>>> bottom.set_color("tab:blue")
>>> bottom.get_color(), left.get_color()
('tab:blue', 'black')
colorbar(mappable, shrink: float = 0.8, format='%.1f', label: str = '', orientation: str | None = None, location: str = 'right', **kwargs) → Colorbar#

Add a colorbar of a plot colored by values to the diagram.

The colorbar takes its space from the Axes of the diagram. Use it to add a colorbar with your own settings to a plot drawn with colorbar=False. This is a wrapper of matplotlib.pyplot.colorbar, called on the figure of the diagram.

Pass the parameters after mappable by keyword. Passing them by position is deprecated since 3.4.0 and emits a FutureWarning; they will be keyword-only in ternary-diagram 4.0.0.

See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.colorbar.html

Parameters:
  • mappable (matplotlib.cm.ScalarMappable) – The plot colored by values that the colorbar describes, such as the return value of scatter() with z, contour(), tripcolor() or heatmapf().

  • shrink (float, optional) – Fraction by which the length of the colorbar is multiplied, relative to the Axes of the diagram, by default 0.8

  • format (str, matplotlib.ticker.Formatter or None, optional) – Format of the tick labels of the colorbar: a %-style format such as "%.2f", a {x}-style format or a matplotlib.ticker.Formatter. If None, matplotlib chooses the format. The default shows one decimal place, by default ‘%.1f’

  • label (str, optional) – Label shown along the colorbar. The empty string shows no label, by default ‘’

  • orientation (str, optional) – Direction of the colorbar, "vertical" or "horizontal". If None, it follows location: vertical on the right or the left, horizontal at the top or the bottom. A given direction must agree with location, or matplotlib raises a TypeError, by default None

  • location (str, optional) – Side of the Axes of the diagram where the colorbar is placed, "right", "left", "top" or "bottom", by default ‘right’

  • **kwargs – Other arguments of matplotlib.pyplot.colorbar (as matplotlib.figure.Figure.colorbar), such as pad, aspect, ticks or extend, passed to matplotlib as they are. ax cannot be given, since the space is always taken from the Axes of the diagram. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.colorbar.html

Returns:

The colorbar, as returned by matplotlib.figure.Figure.colorbar.

Return type:

matplotlib.colorbar.Colorbar

See also

scatter

Points, colored by values with z.

contour

Contours of values.

tripcolor

Triangles painted with values.

heatmapf

A function of the composition painted as a heat map.

Notes

The colorbar is registered to the diagram, so it counts as an existing colorbar when a later plot colored by values decides whether to add a colorbar automatically, as described in the colorbar argument of scatter(), contour(), tripcolor() and heatmapf(). It stops counting once it is removed with Colorbar.remove().

Examples

Color points by their values without the automatic colorbar, and add a colorbar with a label.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> points = td.scatter(
...     [[1, 1, 1], [1, 2, 3], [3, 1, 2]],
...     z=[0.2, 0.5, 0.8],
...     colorbar=False,
... )
>>> cbar = td.colorbar(points, label="Conductivity")
>>> len(fig.axes)
2

Place a colorbar below the diagram, which makes it horizontal, with two decimal places in the tick labels.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> points = td.scatter(
...     [[1, 1, 1], [1, 2, 3], [3, 1, 2]],
...     z=[0.2, 0.5, 0.8],
...     colorbar=False,
... )
>>> cbar = td.colorbar(points, format="%.2f", location="bottom")
>>> cbar.orientation
'horizontal'
contour(vector: ArrayLike, z: ArrayLike | None = None, z_min: Number | None = None, z_max: Number | None = None, fill: bool = True, colorbar: bool | None = None, **kwargs) → TriContourSet#

Draw a contour map of values given at compositions.

The compositions are triangulated and the values z are interpolated between them. This is a wrapper of matplotlib.pyplot.tricontourf with fill=True and of matplotlib.pyplot.tricontour with fill=False.

Pass the parameters after z by keyword. Passing them by position is deprecated since 3.4.0 and emits a FutureWarning; they will be keyword-only in ternary-diagram 4.0.0.

See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tricontourf.html and https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tricontour.html

Parameters:
  • vector (array-like of shape (n, 3)) – Compositions to plot. Each row gives the amounts of the three components in the same order as materials (top, bottom-left, bottom-right; counterclockwise from the top vertex). Rows are normalized, so the sum does not have to be 1.

  • z (array-like of shape (n,)) – Values at the compositions, one per row of vector, from which the contours are drawn. It is required: None, the default, raises a ValueError. NaN and infinite values make matplotlib raise a ValueError too: drop those compositions first, or use tripcolor, which leaves them unpainted.

  • z_min (float, optional) – Lower limit of the automatic levels. If None, the minimum of z is used. With fill=True, the areas whose values are out of the levels are not filled. It cannot be combined with levels, which raises a ValueError, by default None

  • z_max (float, optional) – Upper limit of the automatic levels. If None, the maximum of z is used. With fill=True, the areas whose values are out of the levels are not filled. It cannot be combined with levels, which raises a ValueError, by default None

  • fill (bool, optional) – Whether to fill the areas between the levels. True draws filled contours with tricontourf, and False draws only the contour lines with tricontour, by default True

  • colorbar (bool or None, optional) – Whether to add a colorbar automatically for the contours colored by z. True adds one and False adds none. None keeps the v3.x behavior: it adds one, and when the diagram already has a colorbar, it also emits a FutureWarning once per diagram. In ternary-diagram 4.0.0, None will add none to a diagram that already has a colorbar. The colorbars counted are those added through this TernaryDiagram (automatically or with its colorbar() method) and not removed; colorbars added directly with matplotlib, such as with fig.colorbar, are not counted, by default None

  • flag_cbar (bool, optional) – Deprecated alias of colorbar, interpreted as true or false as before. Passing it emits a FutureWarning; it will be removed in ternary-diagram 4.0.0, so pass colorbar instead. Passing it together with colorbar raises a ValueError. When it is omitted, colorbar decides.

  • **kwargs – Other arguments of matplotlib.pyplot.tricontourf (with fill=True) or matplotlib.pyplot.tricontour (with fill=False), such as levels, cmap, alpha, linewidths or extend, passed to matplotlib as they are. They take precedence over the defaults of this method (cmap="rainbow" and zorder=0). levels (an int for the number of levels chosen by matplotlib, or the increasing values themselves) is used instead of the automatic levels and cannot be combined with z_min or z_max, which raises a ValueError. To draw the contours in one color with colors, also pass cmap=None, since matplotlib does not accept both. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tricontourf.html and https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tricontour.html

Returns:

The filled contours (fill=True) or the contour lines (fill=False), as returned by matplotlib.axes.Axes.tricontourf or matplotlib.axes.Axes.tricontour. Its levels attribute holds the levels used. It can be passed to colorbar() to draw a colorbar of the values.

Return type:

matplotlib.tri.TriContourSet

See also

tripcolor

The triangles between the compositions, painted with their values without interpolation.

heatmapf

A function of the composition painted on a regular triangular lattice.

scatter

Points colored by their values.

colorbar

A colorbar of a plot colored by values.

Notes

Without levels, 101 levels evenly spaced from z_min (or the minimum of z) to z_max (or the maximum of z) are used, so the filled contours look like a continuous color map. When all the values of z are the same, the levels are spread slightly around that value.

The contours are drawn with zorder=0 by default: in front of the heat maps of tripcolor() and heatmapf(), and behind the polygons of fill(), the grid, the border, the tie lines of plot() and the points of scatter(), whatever the order of the calls. Pass zorder to change it.

Examples

Fill the contours of values given at 7 compositions, which adds a colorbar. The 101 automatic levels span the range of the values.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> vector = [
...     [1, 0, 0],
...     [0, 1, 0],
...     [0, 0, 1],
...     [1, 1, 1],
...     [2, 1, 1],
...     [1, 2, 1],
...     [1, 1, 2],
... ]
>>> z = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
>>> contours = td.contour(vector, z=z, colorbar=True)
>>> len(contours.levels)
101

Draw only the contour lines at given levels, in black and without a colorbar.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> vector = [
...     [1, 0, 0],
...     [0, 1, 0],
...     [0, 0, 1],
...     [1, 1, 1],
...     [2, 1, 1],
...     [1, 2, 1],
...     [1, 1, 2],
... ]
>>> z = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]
>>> lines = td.contour(
...     vector,
...     z=z,
...     fill=False,
...     levels=[2, 4, 6],
...     colors="black",
...     cmap=None,
...     colorbar=False,
... )
>>> len(lines.levels)
3
property fig: Figure | SubFigure#

Figure that contains the Axes of the diagram.

It is ax.figure at construction: the figure of the Axes, or the subfigure if the Axes is in a subfigure. It is read-only: assigning to it raises an AttributeError.

Returns:

The figure or subfigure that contains ax.

Return type:

matplotlib.figure.Figure or matplotlib.figure.SubFigure

fill(vector: ArrayLike, **kwargs: Any) → list[Polygon]#

Fill a polygon whose vertices are given as compositions.

This is a wrapper of matplotlib.pyplot.fill.

See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.fill.html

Parameters:
  • vector (array-like of shape (n, 3)) – Compositions of the vertices of the polygon, one row per vertex. Each row represents the ratio of each component (the sum does not have to be 1), in the same order as materials. At least 3 vertices are needed. The vertices are joined in the order given and the polygon is closed automatically; they are not sorted and no convex hull is computed.

  • **kwargs – Properties of matplotlib.patches.Polygon, such as label, facecolor, edgecolor, alpha or hatch, passed to matplotlib as they are. They take precedence over the defaults of this method. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.fill.html

Returns:

A list of one element, the filled polygon, as returned by matplotlib.axes.Axes.fill.

Return type:

list of matplotlib.patches.Polygon

Raises:

ValueError – If the shape of vector is not (n, 3) or it has fewer than 3 vertices.

Notes

The polygon is drawn with zorder=0.5 by default: in front of the contours of contour() and behind the grid, the border, the tie lines of plot(), the points of scatter() and the annotations and the texts of text(). Pass zorder to change it, for example zorder=-0.5 to draw the polygon behind the contours.

Without a color, the polygon is filled with the next color of the matplotlib color cycle, so consecutive calls get different colors. The polygon is opaque by default and hides what is behind it; pass alpha to make it translucent, for example over a contour plot.

Examples

Fill a three-phase region translucently and show it in the legend.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> (polygon,) = td.fill(
...     [[0.5, 0.25, 0.25], [0.25, 0.5, 0.25], [0.25, 0.25, 0.5]],
...     alpha=0.5,
...     label="three-phase region",
... )
>>> legend = td.ax.legend()
property grid_lines_: list[Line2D]#

Lines of the grid drawn now.

Use them to adjust single grid lines. Each access returns a new list. set_grid() replaces the lines with new ones, which drops the changes made to them directly. To hide the grid, use set_grid(visible=False) rather than removing the lines.

Returns:

A new list of the lines of the 1st, 2nd and 3rd materials in this order, each in ascending order of value, empty while the grid is hidden.

Return type:

list of matplotlib.lines.Line2D

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> lines = td.grid_lines_
>>> len(lines)  # 9 values for each of the 3 materials
27
>>> lines[4].set_linestyle("--")  # 0.5 of the 1st material
heatmapf(func: Callable[[ndarray, ndarray, ndarray], ArrayLike], *, scale: int = 50, z_min: Number | None = None, z_max: Number | None = None, shading: Literal['flat', 'gouraud'] = 'flat', colorbar: bool | None = None, **kwargs: Any) → PolyCollection | TriMesh#

Paint a function of the composition over the whole diagram.

The diagram is divided into a regular triangular lattice of small triangles, func is evaluated once at all the evaluation points, and the small triangles are painted from the values. This is a wrapper of matplotlib.pyplot.tripcolor.

See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tripcolor.html

Parameters:
  • func (callable) – Function of the composition, called only once as func(a, b, c). a, b and c are 1-D float arrays of the same length, one element per evaluation point, holding the components in the order of the vertex labels (top, bottom left, bottom right); a + b + c is 1 at each point. It must return one numeric value per evaluation point, as an array of shape (m,), (m, 1) or (1, m), in the same order. Return NaN (or an infinite value) where the function is not defined: the small triangles colored by such values are left unpainted.

  • scale (int, optional) – Number of parts into which each edge of the diagram is divided. The lattice has scale ** 2 small triangles, by default 50

  • z_min (float, optional) – Lower limit of the color scale. vmin is accepted as an alias, and passing both raises a ValueError. If None, the minimum of the finite values returned by func is used. Do not pass it together with norm: leave both z_min and z_max as None so that norm decides the range, since matplotlib raises a ValueError when norm is given with either of them, by default None (the minimum of the values)

  • z_max (float, optional) – Upper limit of the color scale. vmax is accepted as an alias, and passing both raises a ValueError. If None, the maximum of the finite values returned by func is used. Do not pass it together with norm: leave both z_min and z_max as None so that norm decides the range, since matplotlib raises a ValueError when norm is given with either of them, by default None (the maximum of the values)

  • shading ({'flat', 'gouraud'}, optional) – How to evaluate func and paint the small triangles. 'flat' evaluates func at the centroid of each small triangle (never on the edges or at the vertices of the diagram) and paints the triangle with that one color. 'gouraud' evaluates func at the lattice points, including those on the edges and at the vertices, and paints each small triangle with colors varying linearly between the values at its 3 vertices, by default ‘flat’

  • colorbar (bool or None, optional) – Whether to add a colorbar automatically for the triangles colored by the values of func. True adds one and False adds none. None keeps the v3.x behavior: it adds one, and when the diagram already has a colorbar, it also emits a FutureWarning once per diagram. In ternary-diagram 4.0.0, None will add none to a diagram that already has a colorbar. The colorbars counted are those added through this TernaryDiagram (automatically or with its colorbar() method) and not removed; colorbars added directly with matplotlib, such as with fig.colorbar, are not counted. The colorbar added is available as the colorbar attribute of the returned object, by default None

  • **kwargs – Passed to matplotlib as they are, such as cmap, norm, alpha, edgecolors or zorder. They take precedence over the defaults of this method (cmap="rainbow" and zorder=-1). c and facecolors cannot be used because the colors are determined by func, triangles and mask cannot be used because the lattice is fixed (return NaN from func to leave a region unpainted), and the old name flag_cbar is not accepted; use colorbar instead. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tripcolor.html

Returns:

The painted small triangles: a PolyCollection with shading='flat' and a TriMesh with shading='gouraud'. It can be passed to colorbar() to draw a colorbar with the same color range and colormap.

Return type:

matplotlib.collections.PolyCollection or matplotlib.collections.TriMesh

Raises:
  • TypeError – If func is not callable, if scale is not an integer (bool included), if colorbar is neither None, True nor False, or if flag_cbar is passed.

  • ValueError – If scale is less than 1, if func returns values that are not numbers or whose shape is none of (m,), (m, 1) and (1, m), if shading is neither ‘flat’ nor ‘gouraud’, if c, facecolors, triangles or mask is passed, if both z_min and vmin (or z_max and vmax) are passed, or if no triangle can be painted. Nothing is added to the diagram in these cases. Exceptions raised by func itself are propagated as they are, and nothing is added either.

See also

contour

Contours interpolated from the values of the points.

tripcolor

The triangles joining measured compositions painted from their values.

ternary_diagram.utils.get_triangular_lattice

The regular triangular lattice used by this method.

Notes

func receives all the evaluation points at once, so it must work on arrays. Wrap a function that only accepts scalars with numpy.vectorize (td.heatmapf(numpy.vectorize(f))), which calls it once per point. A machine learning model that predicts from the compositions can be passed as lambda a, b, c: model.predict(np.column_stack([a, b, c])).

The evaluation points are the scale ** 2 centroids of the small triangles with shading='flat', and the (scale + 1) * (scale + 2) // 2 lattice points with shading='gouraud'. Use 'flat' for a function that is not defined on the edges of the diagram (for example, one that divides by a component or takes its logarithm), since the centroids never lie on the edges. The 2-D coordinates of the evaluation points are recorded in x_["heatmapf"] and y_["heatmapf"].

The default scale=50 paints 2,500 small triangles. The number of triangles grows as scale ** 2: scale=100 paints 10,000 of them, which still takes well under a second apart from evaluating func, but each triangle is written as its own polygon when the figure is saved in a vector format (PDF, SVG), so the file size and the saving time grow in the same way, especially in SVG, which is not compressed (roughly 0.4 MB for scale=50 and 1.5 MB for scale=100). Save in a raster format (PNG) or pass rasterized=True for large values of scale.

The triangles are drawn with zorder=-1 by default: behind the contours of contour(), the polygons of fill(), the grid, the border, the tie lines of plot() and the points of scatter(), whatever the order of the calls. Pass zorder to change it. Thin lines may appear between the triangles depending on the renderer; pass edgecolors="face" to hide them.

Examples

Paint a function over the whole diagram, which adds a colorbar.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> mesh = td.heatmapf(lambda a, b, c: a * b * c)
>>> type(mesh).__name__
'PolyCollection'
>>> len(mesh.get_paths())
2500
>>> mesh.colorbar is not None
True

Leave the region where the first component is below 0.3 unpainted by returning NaN there, and overlay measured points with the same color range. The later call passes colorbar=False so that only one colorbar is added.

>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> mesh = td.heatmapf(
...     lambda a, b, c: np.where(a < 0.3, np.nan, a),
...     scale=20,
...     z_min=0,
...     z_max=1,
...     shading="gouraud",
... )
>>> type(mesh).__name__
'TriMesh'
>>> points = td.scatter(
...     [[6, 3, 1], [5, 1, 4]], z=[0.6, 0.5], z_min=0, z_max=1,
...     colorbar=False,
... )

Wrap a function that only accepts scalars with numpy.vectorize.

>>> import math
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> from ternary_diagram import TernaryDiagram
>>> def scalar_func(a, b, c):
...     return math.sqrt(a * b)
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> mesh = td.heatmapf(np.vectorize(scalar_func), scale=10)
>>> len(mesh.get_paths())
100
plot(vector: ArrayLike, **kwargs) → list[Line2D]#

Draw a line that joins compositions, such as a tie line.

The compositions are joined by straight segments in the order of the rows. This is a wrapper of matplotlib.pyplot.plot.

See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html

Parameters:
  • vector (array-like of shape (n, 3)) – Compositions to join, in the order of the rows. Each row gives the amounts of the three components in the same order as materials (top, bottom-left, bottom-right; counterclockwise from the top vertex). Rows are normalized, so the sum does not have to be 1.

  • **kwargs – Other arguments of matplotlib.pyplot.plot, such as color, linestyle, linewidth, marker or label, passed to matplotlib as they are. They take precedence over the default of this method (zorder=2). A format string such as "k--" cannot be given; use color and linestyle instead. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html

Returns:

The line, as returned by matplotlib.axes.Axes.plot: a list that holds one matplotlib.lines.Line2D.

Return type:

list of matplotlib.lines.Line2D

See also

fill

A polygon of compositions, filled.

scatter

Points at compositions.

Notes

The line is drawn with zorder=2 by default: in front of the contours of contour(), the polygons of fill(), the grid and the border, and behind the points of scatter(), whatever the order of the calls. Pass zorder to change it.

Examples

Draw a tie line between two compositions as a black dashed line.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> lines = td.plot(
...     [[1, 1, 0], [0, 1, 1]],
...     color="black",
...     linestyle="--",
... )
>>> len(lines)
1

Join three compositions in order, with a marker at each of them.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> lines = td.plot(
...     [[2, 1, 1], [1, 2, 1], [1, 1, 2]],
...     marker="o",
... )
scatter(vector: ArrayLike, z: ArrayLike | None = None, z_min: Number | None = None, z_max: Number | None = None, annotations: list[str] | None = None, colorbar: bool | None = None, *, auto_latex_notation: bool | None = None, **kwargs) → PathCollection#

Plot compositions as scatter points.

This is a wrapper of matplotlib.pyplot.scatter.

Pass the parameters after z by keyword. Passing them by position is deprecated since 3.4.0 and emits a FutureWarning; they will be keyword-only in ternary-diagram 4.0.0.

See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html

Parameters:
  • vector (array-like of shape (n, 3)) – Compositions to plot. Each row gives the amounts of the three components in the same order as materials (top, bottom-left, bottom-right; counterclockwise from the top vertex). Rows are normalized, so the sum does not have to be 1.

  • z (array-like of shape (n,), optional) – Values of the points, one per composition, which determine their colors through the colormap. It cannot be used together with c, which raises a ValueError. If None, the points are not colored by values, by default None

  • z_min (float, optional) – Lower limit of the color scale, used only with z. vmin is accepted as an alias, and passing both raises a ValueError. If None, the minimum of z is used, by default None

  • z_max (float, optional) – Upper limit of the color scale, used only with z. vmax is accepted as an alias, and passing both raises a ValueError. If None, the maximum of z is used, by default None

  • annotations (list, optional) – Texts shown next to the points, one per composition in the same order, each 0.02 to the upper right of its point in fontsize 8. Each str is formatted as described in auto_latex_notation, the same rule as annotate(); items that are not str, such as numbers, are shown as text without formatting. A length different from the number of compositions raises a ValueError. If None, no texts are shown, by default None

  • colorbar (bool or None, optional) – Whether to add a colorbar automatically when the points are colored by z. True adds one and False adds none; without z, no colorbar is added whatever the value. None keeps the v3.x behavior: it adds one, and when the diagram already has a colorbar, it also emits a FutureWarning once per diagram. In ternary-diagram 4.0.0, None will add none to a diagram that already has a colorbar. The colorbars counted are those added through this TernaryDiagram (automatically or with its colorbar() method) and not removed; colorbars added directly with matplotlib, such as with fig.colorbar, are not counted, by default None

  • flag_cbar (bool, optional) – Deprecated alias of colorbar, interpreted as true or false as before. Passing it emits a FutureWarning; it will be removed in ternary-diagram 4.0.0, so pass colorbar instead. Passing it together with colorbar raises a ValueError. When it is omitted, colorbar decides.

  • auto_latex_notation (bool or None, optional) – Whether to write the chemical formulas in annotations in LaTeX notation ("Li2O" to "Li$_{2}$O"). True formats each word that looks like a chemical formula (see ternary_diagram.utils.to_latex_notation()) and keeps the other words, and False shows the text as it is. None keeps the v3.x behavior: every number in a str is written as a subscript ("Sample 1" to "Sample $_{1}$"), except in a text containing $, and a FutureWarning is emitted once per diagram when the display will change. In ternary-diagram 4.0.0, None will follow auto_latex_notation of TernaryDiagram, by default None

  • **kwargs – Other arguments of matplotlib.pyplot.scatter, such as s, marker, c (without z), cmap, alpha or label, passed to matplotlib as they are. They take precedence over the defaults of this method (zorder=3 and, with z, cmap="rainbow"). See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.scatter.html

Returns:

The scatter points, as returned by matplotlib.axes.Axes.scatter. With z, it can be passed to colorbar() to draw a colorbar of the values.

Return type:

matplotlib.collections.PathCollection

See also

contour

Contours interpolated from the values of the points.

tripcolor

The triangles between the points, painted with their values.

annotate

A note at one composition.

colorbar

A colorbar of a plot colored by values.

Notes

The points are drawn with zorder=3 by default: in front of the contours of contour(), the grid, the border and the tie lines of plot(), whatever the order of the calls. Pass zorder to change it. With z, the points are colored with the colormap "rainbow" unless cmap is given.

Examples

Plot compositions with a marker of matplotlib and show a text next to each point.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> points = td.scatter(
...     [[1, 1, 1], [1, 2, 3], [3, 1, 2]],
...     annotations=["a", "b", "c"],
...     marker="x",
... )

Color the points by their values on a fixed color scale, which adds a colorbar.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> points = td.scatter(
...     [[1, 1, 1], [1, 2, 3], [3, 1, 2]],
...     z=[0.2, 0.5, 0.8],
...     z_min=0,
...     z_max=1,
...     colorbar=True,
... )
>>> len(fig.axes)
2
set_axis_labels(labels: Sequence[str | None] | None = None, *, visible: bool | None = None, pad: float | None = None, **kwargs: Any) → list[Text]#

Redraw the axis titles with new settings.

The title of a material is drawn outside the middle of the edge that carries its ticks, parallel to the edge and never upside down: the 1st material on the right edge, the 2nd on the left edge and the 3rd on the bottom edge. No titles are drawn by default. The titles are shown as given, without the conversion to chemical formulas applied to the vertex labels; write mathtext such as "Li$_2$O" for subscripts.

All the titles are removed and drawn again with the settings given, merged with the current ones: settings not given keep their previous values. The other parts and the artists drawn by the user are not changed. If an error is raised, the titles keep their previous settings and artists.

Parameters:
  • labels (sequence of (str or None), or None, optional) – Titles of the 1st, 2nd and 3rd materials, such as a list, a tuple, a numpy array or a pandas Index (for example df.columns[:3] + " / mol%"). A title that is None or "" is not drawn. None keeps the current titles (initially (None, None, None): no titles), by default None

  • visible (bool or None, optional) – Whether to draw the titles. None keeps the current setting (initially True), by default None

  • pad (float or None, optional) – Distance from the midpoints of the edges to the centers of the titles in data coordinates, where each edge has length 1. Positive values move the titles away from the triangle. As the text is sized in points, on a small figure (about 3 by 3 inches) the titles may touch the tick labels: increase pad or decrease fontsize then. None keeps the current setting (initially 0.15), by default None

  • **kwargs – Properties of matplotlib.text.Text, or their aliases such as ha, applied to all titles. They override the defaults (fontsize=12, horizontalalignment="center", verticalalignment="center") and the rotation that differs by edge, and properties not given keep their current values. Once rotation is given, the different rotations of the edges cannot be restored. Arguments of Axes.text that are not properties are not accepted: pass the items of a fontdict as keywords.

Returns:

A new list of the axis titles drawn by this call in the order of the materials, the same titles as axis_labels_. It is empty when the axis titles are hidden or none is given.

Return type:

list of matplotlib.text.Text

Raises:
  • TypeError – If labels is a str, bytes, a mapping, a set or not iterable, if a title is neither a str nor None, if visible is not a bool, if pad is not a real number, if a property is given by both its name and an alias, or if it is x, y or text, which the titles set themselves.

  • ValueError – If labels does not have 3 items, or if pad is not finite.

  • AttributeError – If a keyword is not a property of Text.

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> names = ["Li2O / mol%", "La2O3 / mol%", "TiO2 / mol%"]
>>> titles = td.set_axis_labels(names, fontsize=10)
>>> [title.get_text() for title in titles]
['Li2O / mol%', 'La2O3 / mol%', 'TiO2 / mol%']
>>> titles = td.set_axis_labels([None, None, "TiO2 / mol%"])
>>> [(title.get_text(), title.get_fontsize()) for title in titles]
[('TiO2 / mol%', 10.0)]

axis_label_kw at construction is equivalent to calling set_axis_labels with the same settings right after construction:

>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(
...     ["Li2O", "La2O3", "TiO2"],
...     ax=ax,
...     axis_label_kw={"labels": names, "fontsize": 10},
... )
>>> [title.get_text() for title in td.axis_labels_]
['Li2O / mol%', 'La2O3 / mol%', 'TiO2 / mol%']
set_border(visible: bool | None = None, **kwargs: Any) → list[Line2D]#

Redraw the border of the triangle with new settings.

The lines of the border are removed and drawn again with the settings given, merged with the current ones: settings not given keep their previous values. The other parts and the artists drawn by the user are not changed. If an error is raised, the border keeps its previous settings and lines.

Parameters:
  • visible (bool or None, optional) – Whether to draw the border. None keeps the current setting (initially True), by default None

  • **kwargs – Properties of matplotlib.lines.Line2D, or their aliases such as lw, applied to all lines of the border. They override the defaults (color="black", linewidth=2, linestyle="-", zorder=1), and properties not given keep their current values. Arguments of Axes.plot that are not properties, such as scalex, are not accepted.

Returns:

A new list of the border lines drawn by this call (the bottom, left and right edges), the same lines as border_lines_. It is empty when the border is hidden.

Return type:

list of matplotlib.lines.Line2D

Raises:
  • TypeError – If visible is not a bool, if a property is given by both its name and an alias, or if it is xdata or ydata, which the border sets itself.

  • AttributeError – If a keyword is not a property of Line2D.

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> lines = td.set_border(linewidth=1, linestyle="--")
>>> len(lines), lines[0].get_linewidth()
(3, 1.0)
>>> td.set_border(visible=False)
[]
>>> lines = td.set_border(visible=True)  # keeps the dashed lines
>>> lines[0].get_linestyle()
'--'

border_kw at construction is equivalent to calling set_border with the same settings right after construction:

>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(
...     ["Li2O", "La2O3", "TiO2"],
...     ax=ax,
...     border_kw={"linewidth": 1, "linestyle": "--"},
... )
>>> len(td.border_lines_), td.border_lines_[0].get_linewidth()
(3, 1.0)
set_grid(visible: bool | None = None, *, step: float | None = None, **kwargs: Any) → list[Line2D]#

Redraw the grid with new settings.

The grid lines are drawn for each material at the multiples of step strictly between 0 and 1. The line of a value starts at that value on the tick edge of the material and runs parallel to the edge opposite to the vertex of the material (see the Notes of TernaryDiagram).

All the grid lines are removed and drawn again with the settings given, merged with the current ones: settings not given keep their previous values. The border is then moved back over the new grid lines. The other parts and the artists drawn by the user are not changed. If an error is raised, the grid keeps its previous settings and lines.

Parameters:
  • visible (bool or None, optional) – Whether to draw the grid. None keeps the current setting (initially True), by default None

  • step (float or None, optional) – Interval of the grid lines as a fraction in (0, 1], such as 0.05 for every 5 %. It is independent of the interval of the tick labels. None keeps the current setting (initially 0.1), by default None

  • **kwargs – Properties of matplotlib.lines.Line2D, or their aliases such as lw, applied to all grid lines. They override the defaults (color="gray", linewidth=0.5, zorder=1), and properties not given keep their current values. Arguments of Axes.plot that are not properties, such as scalex, are not accepted.

Returns:

A new list of the grid lines drawn by this call, the same lines as grid_lines_. It is empty when the grid is hidden.

Return type:

list of matplotlib.lines.Line2D

Raises:
  • TypeError – If visible is not a bool, if step is not a real number, if a property is given by both its name and an alias, or if it is xdata or ydata, which the grid sets itself.

  • ValueError – If step is not finite or not in (0, 1].

  • AttributeError – If a keyword is not a property of Line2D.

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> lines = td.set_grid(step=0.05, color="lightgray")
>>> len(lines)  # 19 values for each of the 3 materials
57
>>> lines = td.set_grid(linestyle=":")  # keeps step and color
>>> len(lines), lines[0].get_color()
(57, 'lightgray')

grid_kw at construction is equivalent to calling set_grid with the same settings right after construction:

>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(
...     ["Li2O", "La2O3", "TiO2"],
...     ax=ax,
...     grid_kw={"step": 0.05, "color": "lightgray"},
... )
>>> len(td.grid_lines_)
57
set_ticks(visible: bool | None = None, *, step: float | None = None, fmt: str | Callable[[float], str] | None = None, endpoints: bool | None = None, **kwargs: Any) → list[Text]#

Redraw the tick labels with new settings.

The tick labels of the 1st material (top vertex) are on the right edge, those of the 2nd material (bottom left vertex) on the left edge and those of the 3rd material (bottom right vertex) on the bottom edge. Along each edge the values increase counterclockwise, toward the vertex of the material: from the bottom right vertex to the top vertex on the right edge, from the top vertex to the bottom left vertex on the left edge, and from the bottom left vertex to the bottom right vertex on the bottom edge.

All the tick labels are removed and drawn again with the settings given, merged with the current ones: settings not given keep their previous values. The other parts and the artists drawn by the user are not changed. If an error is raised, the tick labels keep their previous settings and artists.

Parameters:
  • visible (bool or None, optional) – Whether to draw the tick labels. None keeps the current setting (initially True), by default None

  • step (float or None, optional) – Interval of the tick labels as a fraction in (0, 1], such as 0.25 for every 25 %. It is independent of the interval of the grid. None keeps the current setting (initially 0.1), by default None

  • fmt (str, callable or None, optional) – Format of the labels, applied to the values as fractions in [0, 1]: "percent" (0.1 gives "10"), "fraction" (0.1 gives "0.1"), a %-style or {}-style format string such as "%.2f" or "{:.0%}", or a callable that takes the value as a float and returns the label (see ternary_diagram.utils.get_tick_formatter()). A callable is first called when the labels are drawn, not when it is given: given while the labels are hidden, its errors are raised only when they are shown again (pass a valid fmt together with visible=True in that case). None keeps the current setting (initially "percent"), by default None

  • endpoints (bool or None, optional) – Whether to also label the values 0 and 1 at the vertices. None keeps the current setting (initially False), by default None

  • **kwargs – Properties of matplotlib.text.Text, or their aliases such as ha, applied to the labels of all edges. They override the default fontsize=10 and the rotation and the alignments that differ by edge, and properties not given keep their current values. Once rotation or an alignment is given, the different defaults of the edges cannot be restored: rotation=None draws the labels of all edges at 0 degrees. Arguments of Axes.text that are not properties are not accepted: pass the items of a fontdict as keywords.

Returns:

A new list of the tick labels drawn by this call, the same labels as tick_labels_. It is empty when the tick labels are hidden.

Return type:

list of matplotlib.text.Text

Raises:
  • TypeError – If visible or endpoints is not a bool, if step is not a real number, if fmt is neither a str nor a callable, if a property is given by both its name and an alias, or if it is x, y or text, which the tick labels set themselves.

  • ValueError – If step is not finite or not in (0, 1], or if fmt is a str that cannot be used as a format.

  • AttributeError – If a keyword is not a property of Text.

  • Exception – Whatever a callable fmt raises.

Notes

With endpoints=True, the label of 1 of the 2nd material and that of 0 of the 3rd material come close to each other at the bottom left vertex. Adjust or hide one of them through tick_labels_ if they overlap.

The tick labels keep the default zorder of matplotlib for text (3) unless zorder is given. Among artists with the same zorder, the one added to the Axes later is drawn on top, so the redrawn labels are drawn over the artists with zorder 3 drawn before this call, such as scatter points. Give zorder to choose the order.

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> labels = td.set_ticks(step=0.25, fmt="{:.0%}")
>>> len(labels)  # 3 values for each of the 3 materials
9
>>> [label.get_text() for label in labels[::3]]  # the 1st material
['25%', '50%', '75%']
>>> labels = td.set_ticks(endpoints=True)  # keeps step and fmt
>>> [label.get_text() for label in labels[::3]]
['0%', '25%', '50%', '75%', '100%']

tick_kw at construction is equivalent to calling set_ticks with the same settings right after construction:

>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(
...     ["Li2O", "La2O3", "TiO2"],
...     ax=ax,
...     tick_kw={"step": 0.25, "fmt": "{:.0%}"},
... )
>>> [label.get_text() for label in td.tick_labels_[::3]]
['25%', '50%', '75%']
set_vertex_labels(labels: Sequence[str] | None = None, *, visible: bool | None = None, offsets: Sequence[tuple[float, float]] | None = None, **kwargs: Any) → list[Text]#

Redraw the vertex labels with new settings.

The labels are drawn next to the top, bottom left and bottom right vertices, initially with the first 3 materials. Whether they are converted to chemical formulas ("Li2O" is shown as "Li$_{2}$O") is decided by auto_latex_notation at construction, which also applies to the labels given here and cannot be changed by this method.

All the labels are removed and drawn again with the settings given, merged with the current ones: settings not given keep their previous values. The other parts and the artists drawn by the user are not changed. If an error is raised, the labels keep their previous settings and artists.

Parameters:
  • labels (sequence of str or None, optional) – Labels of the top, bottom left and bottom right vertices, such as a list, a tuple, a numpy array or a pandas Index (for example df.columns[:3]). With auto_latex_notation, each label must be a str; without it, any object is shown as Axes.text shows it. None keeps the current labels (initially the first 3 materials), by default None

  • visible (bool or None, optional) – Whether to draw the labels. None keeps the current setting (initially True), by default None

  • offsets (sequence of (float, float) or None, optional) – Offsets (dx, dy) of the labels from the top, bottom left and bottom right vertices in data coordinates, where each edge has length 1: 3 pairs of finite real numbers, such as a list of tuples or a numpy array of shape (3, 2). Convert a pandas DataFrame with to_numpy() first. None keeps the current setting (initially ((0, 0.02), (0, -0.05), (0, -0.05))), by default None

  • **kwargs – Properties of matplotlib.text.Text, or their aliases such as ha, applied to all labels. They override the default fontsize=16 and the alignments that differ by vertex, and properties not given keep their current values. Once an alignment is given, the different alignments of the vertices cannot be restored. Arguments of Axes.text that are not properties are not accepted: pass the items of a fontdict as keywords.

Returns:

A new list of the vertex labels drawn by this call (the top, bottom left and bottom right vertices), the same labels as vertex_labels_. It is empty when the vertex labels are hidden.

Return type:

list of matplotlib.text.Text

Raises:
  • TypeError – If labels, offsets or a pair of offsets is a str, bytes, a mapping, a set or not iterable, if a value of offsets is not a real number, if visible is not a bool, if a property is given by both its name and an alias, or if it is x, y or text, which the labels set themselves.

  • ValueError – If labels or offsets does not have 3 items, if a pair of offsets does not have 2 items, if a value of offsets is not finite, or, with auto_latex_notation, if a label is not a str.

  • AttributeError – If a keyword is not a property of Text.

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> labels = td.set_vertex_labels(fontsize=12)
>>> [label.get_text() for label in labels]
['Li$_{2}$O', 'La$_{2}$O$_{3}$', 'TiO$_{2}$']
>>> offsets = [(0, 0.02), (-0.02, -0.04), (0.02, -0.04)]
>>> labels = td.set_vertex_labels(offsets=offsets)  # keeps fontsize
>>> labels[1].get_position(), labels[1].get_fontsize()
((-0.02, -0.04), 12.0)
>>> labels = td.set_vertex_labels(["Li2O", "La2O3", "SrTiO3"])
>>> labels[2].get_text()
'SrTiO$_{3}$'

vertex_label_kw at construction is equivalent to calling set_vertex_labels with the same settings right after construction. It cannot contain labels, which are given by the materials:

>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(
...     ["Li2O", "La2O3", "TiO2"],
...     ax=ax,
...     vertex_label_kw={"fontsize": 12, "offsets": offsets},
... )
>>> label = td.vertex_labels_[1]
>>> label.get_position(), label.get_fontsize()
((-0.02, -0.04), 12.0)
text(text: str, vector: ArrayLike, *, auto_latex_notation: bool | None = None, **kwargs: Any) → Text#

Place a text at a composition.

This is a wrapper of matplotlib.pyplot.text.

See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html

Parameters:
  • text (str) – Text to be displayed, such as the name of a phase. An object other than str is not formatted and is converted to a string by matplotlib.

  • vector (array-like of shape (3,)) – Composition of the point where the text is placed. It represents the ratio of each component (the sum does not have to be 1), in the same order as materials. Any array-like with exactly three elements, such as one of shape (1, 3), is accepted; other lengths raise a ValueError.

  • auto_latex_notation (bool or None, optional) – Whether to write the chemical formulas in text in LaTeX notation ("Li2O" to "Li$_{2}$O"), with the same rule as annotate() with auto_latex_notation=True (see ternary_diagram.utils.to_latex_notation()). None follows auto_latex_notation of TernaryDiagram, the setting of the diagram also used for the vertex labels (True unless changed). True / False apply only to the text of this call and change neither the setting of the diagram, the vertex labels nor the other calls of text() and annotate(). Pass False to show a word that looks like a chemical formula, such as a sample name "S1", as it is. A text containing $ (mathtext) is always shown as it is, by default None (the setting of the diagram)

  • **kwargs – Properties of matplotlib.text.Text, such as fontsize, color, ha or fontdict, passed to matplotlib as they are. They take precedence over the defaults of this method. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html

Returns:

The text placed at the composition.

Return type:

matplotlib.text.Text

Raises:
  • TypeError – If auto_latex_notation is neither None, True nor False.

  • ValueError – If vector does not have 3 components.

Notes

The center of the text is placed exactly at the composition by default (horizontalalignment="center" and verticalalignment="center"). Pass ha / va (or their full names, also in fontdict) to change it.

The text is drawn with zorder=4 by default: in front of the polygons of fill(), the grid, the border, the tie lines of plot() and the points of scatter(). Pass zorder to change it. The font size is left to matplotlib (rcParams).

Examples

Place the name of a phase on a default diagram, which formats the chemical formulas, and show another text as it is only in that call.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> label = td.text("Li2TiO3", [0.5, 0, 0.5])
>>> label.get_text()
'Li$_{2}$TiO$_{3}$'
>>> plain = td.text(
...     "Phase 1", [0.2, 0.4, 0.4], auto_latex_notation=False
... )
>>> plain.get_text()
'Phase 1'

On a diagram that does not format the chemical formulas, the text is shown as it is unless auto_latex_notation=True is passed.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(
...     ["Li2O", "La2O3", "TiO2"], ax=ax, auto_latex_notation=False
... )
>>> label = td.text("Li2TiO3", [0.5, 0, 0.5])
>>> label.get_text()
'Li2TiO3'
>>> formula = td.text(
...     "Li2TiO3", [0.5, 0, 0.5], auto_latex_notation=True
... )
>>> formula.get_text()
'Li$_{2}$TiO$_{3}$'
property tick_labels_: list[Text]#

Tick labels drawn now.

Use them to adjust single labels, such as one of the labels that come close at the bottom left vertex with endpoints=True (see set_ticks()). Each access returns a new list. set_ticks() replaces the labels with new ones, which drops the changes made to them directly. To hide the tick labels, use set_ticks(visible=False) rather than removing the labels.

Returns:

A new list of the tick labels in ascending order of value, each value for the 1st, 2nd and 3rd materials in this order, empty while the tick labels are hidden.

Return type:

list of matplotlib.text.Text

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> labels = td.tick_labels_
>>> len(labels)  # 9 values for each of the 3 materials
27
>>> [label.get_text() for label in labels[:3]]  # 0.1 of each
['10', '10', '10']
>>> labels[12].set_color("tab:red")  # 0.5 of the 1st material
tripcolor(vector: ArrayLike, z: ArrayLike, *, z_min: Number | None = None, z_max: Number | None = None, shading: Literal['flat', 'gouraud'] = 'flat', colorbar: bool | None = None, **kwargs: Any) → PolyCollection | TriMesh#

Paint the triangles joining the compositions with their values.

The compositions are joined into triangles and each triangle is painted from the values z of its 3 vertices, without interpolating values elsewhere. This is a wrapper of matplotlib.pyplot.tripcolor.

See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tripcolor.html

Parameters:
  • vector (array-like of shape (n, 3)) – Compositions of the points, one row per point. Each row represents the ratio of each component (the sum does not have to be 1), in the same order as materials.

  • z (array-like of shape (n,)) – Values of the points, one per composition, which determine the colors. A NaN or infinite value, or a masked value of a masked array, leaves every triangle having that point as a vertex unpainted.

  • z_min (float, optional) – Lower limit of the color scale. vmin is accepted as an alias, and passing both raises a ValueError. If None, the minimum of the finite values of z is used. Do not pass it together with norm: leave both z_min and z_max as None so that norm decides the range, since matplotlib raises a ValueError when norm is given with either of them, by default None (the minimum of z)

  • z_max (float, optional) – Upper limit of the color scale. vmax is accepted as an alias, and passing both raises a ValueError. If None, the maximum of the finite values of z is used. Do not pass it together with norm: leave both z_min and z_max as None so that norm decides the range, since matplotlib raises a ValueError when norm is given with either of them, by default None (the maximum of z)

  • shading ({'flat', 'gouraud'}, optional) – How to paint each triangle. 'flat' paints it with one color, that of the mean of z at its 3 vertices. 'gouraud' paints it with colors varying linearly between the values of z at its 3 vertices, by default ‘flat’

  • colorbar (bool or None, optional) – Whether to add a colorbar automatically for the triangles colored by z. True adds one and False adds none. None keeps the v3.x behavior: it adds one, and when the diagram already has a colorbar, it also emits a FutureWarning once per diagram. In ternary-diagram 4.0.0, None will add none to a diagram that already has a colorbar. The colorbars counted are those added through this TernaryDiagram (automatically or with its colorbar() method) and not removed; colorbars added directly with matplotlib, such as with fig.colorbar, are not counted. The colorbar added is available as the colorbar attribute of the returned object, by default None

  • **kwargs – Passed to matplotlib as they are, such as cmap, norm, alpha, edgecolors or zorder. They take precedence over the defaults of this method (cmap="rainbow" and zorder=-1). triangles (indices of the 3 points of each triangle, shape (ntri, 3)) replaces the automatic triangulation, and mask (boolean, shape (ntri,)) leaves the triangles that are true unpainted. c and facecolors cannot be used because the colors are determined by z, and the old name flag_cbar is not accepted; use colorbar instead. See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tripcolor.html

Returns:

The painted triangles: a PolyCollection with shading='flat' and a TriMesh with shading='gouraud'. It can be passed to colorbar() to draw a colorbar with the same color range and colormap.

Return type:

matplotlib.collections.PolyCollection or matplotlib.collections.TriMesh

Raises:
  • TypeError – If colorbar is neither None, True nor False, or if flag_cbar is passed.

  • ValueError – If z is None or does not have one value per composition, if shading is neither ‘flat’ nor ‘gouraud’, if c or facecolors is passed, if both z_min and vmin (or z_max and vmax) are passed, if the compositions cannot be triangulated automatically (fewer than 3 distinct compositions, or all of them on one straight line), or if no triangle can be painted. Nothing is added to the diagram in these cases.

Warns:

UserWarning – If some compositions are the same after normalization. Only the value of one of them is drawn.

See also

contour

Contours interpolated from the values of the points.

scatter

Points colored by their values.

heatmapf

A function painted on a regular triangular lattice.

ternary_diagram.utils.get_triangular_lattice

The regular triangular lattice used by heatmapf().

Notes

Without triangles, the compositions are triangulated automatically (Delaunay), so only the inside of their convex hull is painted and nothing is painted outside it. Compositions that are the same after normalization are used only once: aggregate their values (for example, by averaging them) before calling this method.

With shading='flat', each triangle shows the mean of the values at its 3 vertices, so no triangle may reach the colors at the ends of the colorbar, whose range is that of z itself.

The triangles are drawn with zorder=-1 by default: behind the contours of contour(), the polygons of fill(), the grid, the border, the tie lines of plot() and the points of scatter(), whatever the order of the calls. Pass zorder to change it. Thin lines may appear between the triangles depending on the renderer; pass edgecolors="face" to hide them.

Examples

Paint the triangles joining the 3 vertices and a point inside the diagram, which adds a colorbar.

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> mesh = td.tripcolor(
...     [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 1]],
...     [1.0, 2.0, 3.0, 4.0],
... )
>>> type(mesh).__name__
'PolyCollection'
>>> len(mesh.get_paths())
3
>>> mesh.colorbar is not None
True
property vertex_labels_: list[Text]#

Vertex labels drawn now.

Use them to adjust a single label. Each access returns a new list. set_vertex_labels() replaces the labels with new ones, which drops the changes made to them directly. To hide the labels, use set_vertex_labels(visible=False) rather than removing them.

Returns:

A new list of the labels of the top, bottom left and bottom right vertices, empty while the vertex labels are hidden.

Return type:

list of matplotlib.text.Text

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram import TernaryDiagram
>>> fig, ax = plt.subplots(layout="constrained")
>>> td = TernaryDiagram(["Li2O", "La2O3", "TiO2"], ax=ax)
>>> top, left, right = td.vertex_labels_
>>> top.get_text()
'Li$_{2}$O'
>>> top.set_color("tab:red")

Submodules#

ternary_diagram.utils module#

ternary_diagram.utils.TickFormat#

a name ("percent" or "fraction"), a format string or a callable that takes a value in [0, 1] and returns its label.

Type:

Format of the tick labels accepted by get_tick_formatter()

alias of str | Callable[[float], str]

ternary_diagram.utils.check_1d_vector(vector: ArrayLike, scale: bool = True) → ndarray#

Check a single composition and return it as a row of a 2D array.

Parameters:
  • vector (array-like of shape (3,)) – One composition: the amounts of the three components in the order top, bottom-left, bottom-right (counterclockwise from the top vertex). Any array-like with exactly three elements is accepted, because it is flattened first.

  • scale (bool, optional) – Whether to divide the composition by its sum so that it sums to 1. A composition whose sum is 0 becomes NaN. If False, the values are returned as they are, by default True

Returns:

The composition as the only row, normalized if scale is True.

Return type:

numpy.ndarray of shape (1, 3)

Raises:

ValueError – If vector does not have exactly three elements.

Examples

>>> from ternary_diagram.utils import check_1d_vector
>>> check_1d_vector([2, 2, 4])
array([[0.25, 0.25, 0.5 ]])
>>> check_1d_vector([1, 2, 3], scale=False)
array([[1, 2, 3]])
>>> check_1d_vector([1, 2])
Traceback (most recent call last):
    ...
ValueError: `vector`'s length must be 3.
ternary_diagram.utils.check_2d_vector(vector: ArrayLike, scale: bool = True) → ndarray#

Check the shape of compositions and normalize each row.

Parameters:
  • vector (array-like of shape (n, 3)) – Compositions, one per row. Each row gives the amounts of the three components in the order top, bottom-left, bottom-right (counterclockwise from the top vertex).

  • scale (bool, optional) – Whether to divide each row by its sum so that it sums to 1. A row whose sum is 0 becomes NaN. If False, the values are returned as they are, by default True

Returns:

The compositions, normalized if scale is True.

Return type:

numpy.ndarray of shape (n, 3)

Raises:

ValueError – If vector is not two-dimensional with three columns.

Examples

>>> from ternary_diagram.utils import check_2d_vector
>>> check_2d_vector([[1, 1, 2], [3, 0, 1]])
array([[0.25, 0.25, 0.5 ],
       [0.75, 0.  , 0.25]])
>>> check_2d_vector([[1, 1, 2]], scale=False)
array([[1, 1, 2]])
>>> check_2d_vector([1, 1, 2])
Traceback (most recent call last):
    ...
ValueError: `vector`'s shape must be (n, 3), but got (3,).
ternary_diagram.utils.check_ax(ax: Axes | None) → Axes#

Return the Axes to draw on.

Parameters:

ax (matplotlib.axes.Axes or None) – Axes to draw on. If None, the current Axes (plt.gca()) is used, which creates a figure and an Axes when there is none.

Returns:

ax itself if it is an Axes, otherwise the current Axes.

Return type:

matplotlib.axes.Axes

Raises:

TypeError – If ax is neither None nor a matplotlib.axes.Axes.

Examples

>>> import matplotlib.pyplot as plt
>>> from ternary_diagram.utils import check_ax
>>> fig, ax = plt.subplots(layout="constrained")
>>> check_ax(ax) is ax
True
>>> check_ax(None) is ax
True
>>> check_ax(fig)
Traceback (most recent call last):
    ...
TypeError: `ax` is None or Axes object.
This `ax` is (<class 'matplotlib.figure.Figure'>).
ternary_diagram.utils.check_bool(value: object, name: str) → bool#

Check that a value is True or False.

Parameters:
  • value (object) – The value passed to the argument being checked. Only bool and numpy.bool_ are accepted.

  • name (str) – The name of the argument being checked, shown in the error message.

Returns:

value converted to the built-in bool.

Return type:

bool

Raises:

TypeError – If value is neither bool nor numpy.bool_, including None, 0, 1 and strings.

Examples

>>> from ternary_diagram.utils import check_bool
>>> import numpy as np
>>> check_bool(True, "visible")
True
>>> check_bool(np.bool_(False), "visible")
False
>>> check_bool(None, "visible")
Traceback (most recent call last):
    ...
TypeError: `visible` must be True or False, but got None.
>>> check_bool("yes", "visible")
Traceback (most recent call last):
    ...
TypeError: `visible` must be True or False, but got 'yes'.
ternary_diagram.utils.check_optional_bool(value: object, name: str) → bool | None#

Check that a value is None, True or False.

Parameters:
  • value (object) – The value passed to the argument being checked. None, bool and numpy.bool_ are accepted.

  • name (str) – The name of the argument being checked, shown in the error message.

Returns:

None if value is None, otherwise value converted to the built-in bool.

Return type:

bool or None

Raises:

TypeError – If value is neither None, bool nor numpy.bool_.

Examples

>>> from ternary_diagram.utils import check_optional_bool
>>> import numpy as np
>>> print(check_optional_bool(None, "tight_layout"))
None
>>> check_optional_bool(False, "tight_layout")
False
>>> check_optional_bool(np.bool_(True), "tight_layout")
True
>>> check_optional_bool(1, "tight_layout")
Traceback (most recent call last):
    ...
TypeError: `tight_layout` must be None, True or False, but got 1.
ternary_diagram.utils.get_axis_label_position(component: int, pad: float) → tuple[float, float, float]#

Return the position and rotation of the axis title of a component.

The title is placed outside the edge that carries the ticks of component (see get_edge_points()): at the midpoint of the edge moved by pad along the outward unit normal of the edge. The rotation makes the text parallel to the edge and never upside down.

Parameters:
  • component (int) – Index of the component in the order of the vertices: 0 (top), 1 (bottom left) or 2 (bottom right).

  • pad (float) – Distance from the midpoint of the edge to the title in data coordinates, where each edge has length 1. Positive values move the title away from the triangle. bool is not accepted.

Returns:

  • x (float) – x coordinate of the title.

  • y (float) – y coordinate of the title.

  • rotation (float) – Rotation of the title in degrees: 300 for the right edge (component 0), 60 for the left edge (component 1) and 0 for the bottom edge (component 2).

Raises:
  • TypeError – If pad is not a real number (bool is rejected).

  • ValueError – If component is not 0, 1 or 2 (bool and floats are rejected), or if pad is not finite.

Examples

>>> from ternary_diagram.utils import get_axis_label_position
>>> get_axis_label_position(2, 0.15)
(0.5, -0.15, 0.0)
>>> x, y, rotation = get_axis_label_position(0, 0.15)
>>> round(x, 3), round(y, 3), rotation
(0.88, 0.508, 300.0)
>>> x, y, rotation = get_axis_label_position(1, 0.15)
>>> round(x, 3), round(y, 3), rotation
(0.12, 0.508, 60.0)
ternary_diagram.utils.get_edge_points(values: ArrayLike, component: int) → tuple[ndarray, ndarray]#

Return the points for values on the edge of a component’s ticks.

The ticks of component k are on the edge where component (k + 1) % 3 is 0: the right edge for component 0 (top vertex), the left edge for component 1 (bottom-left vertex) and the bottom edge for component 2 (bottom-right vertex). Along each edge the values increase counterclockwise, from 0 at the vertex of component (k + 2) % 3 to 1 at the vertex of component k. The points are computed with three2two().

Parameters:
  • values (ArrayLike) – Values of component as fractions in [0, 1], given as a scalar or a one-dimensional sequence.

  • component (int) – Index of the component in the order of the vertices: 0 (top), 1 (bottom left) or 2 (bottom right).

Returns:

  • x (numpy.ndarray) – x coordinates of the points, a one-dimensional array with one element per value.

  • y (numpy.ndarray) – y coordinates of the points, with the same shape as x.

Raises:

ValueError – If component is not 0, 1 or 2 (bool and floats are rejected), or if values has more than one dimension.

Examples

>>> from ternary_diagram.utils import get_edge_points
>>> x, y = get_edge_points([0.0, 0.5, 1.0], 2)
>>> x.tolist(), y.tolist()
([0.0, 0.5, 1.0], [0.0, 0.0, 0.0])
>>> x, y = get_edge_points([0.0, 1.0], 0)
>>> x.round(3).tolist(), y.round(3).tolist()
([1.0, 0.5], [0.0, 0.866])
>>> get_edge_points([0.5], 3)
Traceback (most recent call last):
    ...
ValueError: `component` must be 0, 1 or 2, but got 3.
ternary_diagram.utils.get_grid_segments(values: ArrayLike, component: int) → tuple[ndarray, ndarray]#

Return the end points of the iso-composition lines of a component.

The line where component (k) equals a value runs between two edges. It starts on the edge where component (k + 1) % 3 is 0, which carries the ticks of component (see get_edge_points()), and ends on the edge where component (k + 2) % 3 is 0. The points are computed with three2two().

Parameters:
  • values (ArrayLike) – Values of component on the lines as fractions in [0, 1], given as a scalar or a one-dimensional sequence.

  • component (int) – Index of the component in the order of the vertices: 0 (top), 1 (bottom left) or 2 (bottom right).

Returns:

  • xs (numpy.ndarray) – x coordinates of the end points, an array of shape (n, 2) where n is the number of values. Row i is the line of the i-th value: column 0 is its start on the tick edge and column 1 its end.

  • ys (numpy.ndarray) – y coordinates of the end points, with the same layout as xs.

Raises:

ValueError – If component is not 0, 1 or 2 (bool and floats are rejected), or if values has more than one dimension.

Examples

>>> from ternary_diagram.utils import get_grid_segments
>>> xs, ys = get_grid_segments([0.5], 2)
>>> xs.round(3).tolist(), ys.round(3).tolist()
([[0.5, 0.75]], [[0.0, 0.433]])
>>> xs, ys = get_grid_segments([0.25, 0.5, 0.75], 0)
>>> xs.shape, ys.shape
((3, 2), (3, 2))
ternary_diagram.utils.get_label(compound_name: str) → str#

Write every number in a compound name as a LaTeX subscript.

Each number, a run of digits with an optional decimal part such as 2 or 0.5, is wrapped in $_{ and }$ wherever it appears. The text is not checked to be a chemical formula, so the numbers of other words ("Sample 1") and of text already written in mathtext are converted as well. The vertex labels are formatted with this function when auto_latex_notation of TernaryDiagram is True. To convert only the words that look like chemical formulas, use to_latex_notation().

Parameters:

compound_name (str) – Name of a compound, such as "Li2O" or "(LiLa)0.5TiO3".

Returns:

compound_name with every number written as a subscript.

Return type:

str

Raises:

ValueError – If compound_name is not a str.

Examples

>>> from ternary_diagram.utils import get_label
>>> get_label("Li2O")
'Li$_{2}$O'
>>> get_label("(LiLa)0.5TiO3")
'(LiLa)$_{0.5}$TiO$_{3}$'
>>> get_label("Sample 1")
'Sample $_{1}$'
ternary_diagram.utils.get_tick_formatter(fmt: str | Callable[[float], str]) → Callable[[float], str]#

Return a function that turns a tick value into its label.

Parameters:

fmt (str or callable) –

Format of the labels. The values given to the returned function are fractions in [0, 1]. One of:

  • "percent": the value as a percentage without unnecessary digits (0.1 -> "10", 0.025 -> "2.5", 1 -> "100").

  • "fraction": the value as a fraction (0.1 -> "0.1").

  • Any other str: a format string applied to the fraction. %-style ("%.2f") is tried first, and {}-style ("{:.0%}", "{x:.1f}") is used if it fails.

  • A callable that takes the fraction as a float. Its return value is converted with str, and its exceptions propagate when the returned function is called.

Returns:

Function that takes a value and returns its label as a str.

Return type:

callable

Raises:
  • TypeError – If fmt is neither a str nor a callable.

  • ValueError – If fmt is a str that is neither "percent" nor "fraction" and either contains neither % nor { or cannot format the trial value 0.5 in either style.

Examples

>>> from ternary_diagram.utils import get_tick_formatter
>>> percent = get_tick_formatter("percent")
>>> [percent(value) for value in (0.1, 0.025, 1.0)]
['10', '2.5', '100']
>>> get_tick_formatter("fraction")(0.1)
'0.1'
>>> get_tick_formatter("%.2f")(0.1)
'0.10'
>>> get_tick_formatter("{:.0%}")(0.1)
'10%'
>>> get_tick_formatter("{x:.1f}")(0.1)
'0.1'
>>> get_tick_formatter(lambda value: f"{value * 100:.1f}%")(0.1)
'10.0%'
ternary_diagram.utils.get_tick_values(step: float, endpoints: bool = False) → ndarray#

Return the values of the ticks or the grid lines for an interval.

The values are the multiples of step in the open interval (0, 1) in ascending order, rounded to 12 decimal places to suppress floating-point errors.

Parameters:
  • step (float) – Interval between the values as a fraction in the range 0 < step <= 1. bool is not accepted.

  • endpoints (bool, optional) – Whether to add 0 and 1 at both ends, by default False

Returns:

One-dimensional array of the values as floats in ascending order. It is empty when step is 1 and endpoints is False.

Return type:

numpy.ndarray

Raises:
  • TypeError – If step is not a real number (bool is rejected), or if endpoints is neither True nor False.

  • ValueError – If step is not finite or not in the range 0 < step <= 1.

Examples

>>> from ternary_diagram.utils import get_tick_values
>>> get_tick_values(0.25).tolist()
[0.25, 0.5, 0.75]
>>> get_tick_values(0.1).tolist()
[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
>>> len(get_tick_values(0.05))
19
>>> get_tick_values(0.25, endpoints=True).tolist()
[0.0, 0.25, 0.5, 0.75, 1.0]
>>> get_tick_values(1).tolist()
[]
>>> get_tick_values(0)
Traceback (most recent call last):
    ...
ValueError: `step` must satisfy 0 < step <= 1, but got 0.
ternary_diagram.utils.get_triangular_lattice(scale: int) → tuple[ndarray, ndarray]#

Return a regular triangular lattice with scale parts on each edge.

The lattice points are all the compositions whose components are multiples of 1 / scale and sum to 1, and the small triangles cover the whole diagram without overlaps or gaps, all with the same area.

Parameters:

scale (int) – Number of parts into which each edge is divided, 1 or greater. Integer types of numpy are accepted, bool is not.

Returns:

  • vertices (numpy.ndarray) – Compositions of the lattice points, a float array of shape ((scale + 1) * (scale + 2) // 2, 3). Each row is (i, j, k) / scale with non-negative integers i + j + k = scale, and the columns are in the order of the vertices of the diagram (top, bottom left, bottom right). The rows are in descending i, then descending j: from the top row to the bottom row of the diagram, and from left to right within a row.

  • triangles (numpy.ndarray) – Small triangles as the row numbers of three vertices, an array of numpy.intp with shape (scale ** 2, 3). The scale * (scale + 1) // 2 upward triangles come first, each as its top, bottom-left and bottom-right vertices, followed by the scale * (scale - 1) // 2 downward triangles, each as its bottom, upper-right and upper-left vertices. Every triangle is counterclockwise in the coordinates of three2two(). Within each group the triangles are ordered from the top row to the bottom row of the diagram, and from left to right within a row.

Raises:
  • TypeError – If scale is not an integer (bool is rejected).

  • ValueError – If scale is less than 1.

Examples

>>> from ternary_diagram.utils import get_triangular_lattice
>>> vertices, triangles = get_triangular_lattice(1)
>>> vertices.tolist()
[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
>>> triangles.tolist()
[[0, 1, 2]]
>>> vertices, triangles = get_triangular_lattice(2)
>>> vertices.shape, triangles.shape
((6, 3), (4, 3))
>>> for row in vertices.tolist():
...     print(row)
[1.0, 0.0, 0.0]
[0.5, 0.5, 0.0]
[0.5, 0.0, 0.5]
[0.0, 1.0, 0.0]
[0.0, 0.5, 0.5]
[0.0, 0.0, 1.0]
>>> triangles.tolist()
[[0, 1, 2], [1, 3, 4], [2, 4, 5], [4, 2, 1]]
>>> get_triangular_lattice(0)
Traceback (most recent call last):
    ...
ValueError: `scale` must be 1 or greater, but got 0.
ternary_diagram.utils.is_chemical_formula(word: str) → bool#

Tell whether a word looks like a chemical formula.

A word looks like a chemical formula when it is made only of element-like symbols (an upper case letter followed by at most one lower case letter, such as Li or O), numbers (2, 0.5) and balanced parentheses, and starts with a symbol or an opening parenthesis. The symbols are not checked against the periodic table, so placeholder materials such as AB2 also look like chemical formulas.

Parameters:

word (str) – A word without white space, such as "Li2O".

Returns:

True if word looks like a chemical formula.

Return type:

bool

Raises:

TypeError – If word is not a str.

Examples

>>> from ternary_diagram.utils import is_chemical_formula
>>> is_chemical_formula("Li2O")
True
>>> is_chemical_formula("(LiLa)0.5TiO3")
True
>>> is_chemical_formula("Sample")
False
>>> is_chemical_formula("1")
False
ternary_diagram.utils.three2two(vector: ArrayLike) → tuple[ndarray, ndarray]#

Convert compositions to 2D coordinates on the ternary diagram.

The triangle has the vertices top (0.5, sqrt(3) / 2), bottom-left (0, 0) and bottom-right (1, 0), which correspond to the first, second and third components.

Parameters:

vector (array-like of shape (n, 3)) – Compositions whose rows sum to 1, one per row, in the order top, bottom-left, bottom-right (counterclockwise from the top vertex). The rows are not normalized here; pass the output of check_2d_vector() to convert amounts that do not sum to 1.

Returns:

  • x (numpy.ndarray of shape (n,)) – Horizontal coordinates of the compositions.

  • y (numpy.ndarray of shape (n,)) – Vertical coordinates of the compositions.

Examples

>>> from ternary_diagram.utils import check_2d_vector, three2two
>>> x, y = three2two([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
>>> x
array([0.5, 0. , 1. ])
>>> y
array([0.8660254, 0.       , 0.       ])
>>> three2two(check_2d_vector([[2, 2, 4]]))
(array([0.625]), array([0.21650635]))
ternary_diagram.utils.to_latex_notation(text: str) → str#

Write the numbers of the chemical formulas in a text as subscripts.

The text is split at white space, and each word that looks like a chemical formula (see is_chemical_formula()) is converted by get_label(). The other words and the white space are kept as they are. A text containing $ is returned unchanged, because it is already written in mathtext.

Parameters:

text (str) – A text such as a label of a point, like "LiF + Li2O".

Returns:

text with the chemical formulas in LaTeX notation.

Return type:

str

Raises:

TypeError – If text is not a str.

Examples

>>> from ternary_diagram.utils import to_latex_notation
>>> to_latex_notation("Li2O")
'Li$_{2}$O'
>>> to_latex_notation("LiF + Li2O")
'LiF + Li$_{2}$O'
>>> to_latex_notation("Sample 1")
'Sample 1'
>>> to_latex_notation("$x_1$")
'$x_1$'