### Install mpltern from GitHub Source: https://mpltern.readthedocs.io/en/latest/_sources/installation.rst.txt Install the development version of mpltern directly from its GitHub repository. ```console python -m pip install -U git+https://github.com/yuzie007/mpltern.git ``` -------------------------------- ### Install mpltern from Conda Source: https://mpltern.readthedocs.io/en/latest/installation.html Install the latest released version of mpltern from conda-forge. Ensure conda-forge is added as a channel. ```bash conda config --add channels conda-forge conda install mpltern ``` -------------------------------- ### Install mpltern Development Version from GitHub Source: https://mpltern.readthedocs.io/en/latest/installation.html Install the development version of mpltern directly from its GitHub repository using pip. ```bash python -m pip install -U git+https://github.com/yuzie007/mpltern.git ``` -------------------------------- ### Install mpltern from PyPI Source: https://mpltern.readthedocs.io/en/latest/_sources/installation.rst.txt Use this command to install the latest released version of mpltern from the Python Package Index. ```console python -m pip install -U mpltern ``` -------------------------------- ### Add conda-forge channel and install mpltern Source: https://mpltern.readthedocs.io/en/latest/_sources/installation.rst.txt Configure your conda environment to use the conda-forge channel and then install mpltern. ```console conda config --add channels conda-forge conda install mpltern ``` -------------------------------- ### mpltern Plotting Region Fitting Examples Source: https://mpltern.readthedocs.io/en/latest/_downloads/27c1ed65d83ebb5a7a7d0d855966cb47/02.fit.ipynb This code snippet demonstrates the different 'fit' options ('rectangle', 'triangle', 'none') available in mpltern's `set_ternary_lim` function. It plots a spiral dataset for each fit type, showing how the plotting region is adjusted. Requires matplotlib and mpltern datasets. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_spiral def set_labels(ax): """Set ternary-axis labels.""" ax.set_tlabel('Top') ax.set_llabel('Left') ax.set_rlabel('Right') ax.taxis.set_label_position("tick1") ax.laxis.set_label_position("tick1") ax.raxis.set_label_position("tick1") def plot_frame(ax): ax.fill( [0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 1.0, 0.0], ec="r", fc="none", ls=":", transform=ax.transAxes, clip_on=False, zorder=1.0, ) ax.fill( [0.5, 0.0, 1.0], [1.0, 0.0, 0.0], ec="b", fc="none", ls=":", transform=ax.transAxes, clip_on=False, zorder=1.0, ) fig = plt.figure(figsize=(10.8, 4.8)) fig.subplots_adjust(left=0.075, right=0.925, wspace=0.25) fits = ["rectangle", "triangle", "none"] for i, fit in enumerate(fits): ax = fig.add_subplot(1, 3, i + 1, projection='ternary') ax.plot(*get_spiral(), c="k") ax.set_ternary_lim( 0.1, 0.7, # tmin, tmax 0.1, 0.7, # lmin, lmax 0.1, 0.7, # rmin, rmax fit=fit, ) set_labels(ax) ax.set_title(f"fit='{fit}'", pad=42) plot_frame(ax) plt.show() ``` -------------------------------- ### Ternary Contour Plots Source: https://mpltern.readthedocs.io/en/latest/_downloads/96ad35c4f29e37a0c5b937c9af02b25f/02.contour.ipynb Generates both `tricontour` and `tricontourf` plots on a ternary diagram. This example requires importing numpy, matplotlib.pyplot, and get_shanon_entropies from mpltern.datasets. It also demonstrates setting color bar scales and labels. ```python import numpy as np import matplotlib.pyplot as plt from mpltern.datasets import get_shanon_entropies t, l, r, v = get_shanon_entropies() fig = plt.figure(figsize=(10.8, 4.8)) fig.subplots_adjust(left=0.075, right=0.85, wspace=0.3) # These values are for controlling the color-bar scale, and here they are # explicitly given just to make the same color-bar scale for all the plots. # In general, you may not need to explicitly specify them. vmin = 0.0 vmax = 1.2 levels = np.linspace(vmin, vmax, 7) ax = fig.add_subplot(1, 2, 1, projection='ternary') cs = ax.tricontour(t, l, r, v, levels=levels) ax.clabel(cs) ax.set_title("tricontour") cax = ax.inset_axes([1.05, 0.1, 0.05, 0.9], transform=ax.transAxes) colorbar = fig.colorbar(cs, cax=cax) colorbar.set_label('Entropy', rotation=270, va='baseline') ax = fig.add_subplot(1, 2, 2, projection='ternary') cs = ax.tricontourf(t, l, r, v, levels=levels) ax.set_title("tricontourf") cax = ax.inset_axes([1.05, 0.1, 0.05, 0.9], transform=ax.transAxes) colorbar = fig.colorbar(cs, cax=cax) colorbar.set_label('Entropy', rotation=270, va='baseline') plt.show() ``` -------------------------------- ### Ternary Plotting Region Fitting Example Source: https://mpltern.readthedocs.io/en/latest/gallery/limits/02.fit.html This snippet demonstrates how to use the 'fit' option in `set_ternary_lim` to control the plotting region. It shows three different fitting modes: 'rectangle' (default), 'triangle', and 'none'. The `plot_frame` function is used to visualize the boundaries. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_spiral def set_labels(ax): """Set ternary-axis labels.""" ax.set_tlabel('Top') ax.set_llabel('Left') ax.set_rlabel('Right') ax.taxis.set_label_position("tick1") ax.laxis.set_label_position("tick1") ax.raxis.set_label_position("tick1") def plot_frame(ax): ax.fill( [0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 1.0, 0.0], ec="r", fc="none", ls=":", transform=ax.transAxes, clip_on=False, zorder=1.0, ) ax.fill( [0.5, 0.0, 1.0], [1.0, 0.0, 0.0], ec="b", fc="none", ls=":", transform=ax.transAxes, clip_on=False, zorder=1.0, ) fig = plt.figure(figsize=(10.8, 4.8)) fig.subplots_adjust(left=0.075, right=0.925, wspace=0.25) fits = ["rectangle", "triangle", "none"] for i, fit in enumerate(fits): ax = fig.add_subplot(1, 3, i + 1, projection='ternary') ax.plot(*get_spiral(), c="k") ax.set_ternary_lim( 0.1, 0.7, # tmin, tmax 0.1, 0.7, # lmin, lmax 0.1, 0.7, # rmin, rmax fit=fit, ) set_labels(ax) ax.set_title(f"fit='{fit}'", pad=42) plot_frame(ax) plt.show() ``` -------------------------------- ### Plotting Lines and Curves on Ternary Plot Source: https://mpltern.readthedocs.io/en/latest/_downloads/5e6f20e02c879cc16d98d723b1ecdea9/00.line_and_curve.ipynb Plots multiple lines and curves on a ternary diagram. Includes examples of straight lines, lines with markers, dashed lines with markers, and a custom spiral curve. Requires importing matplotlib.pyplot and mpltern.datasets. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_spiral ax = plt.subplot(projection='ternary') ax.plot([0.8, 0.6], [0.1, 0.2], [0.1, 0.2]) ax.plot([0.1, 0.2], [0.8, 0.6], [0.1, 0.2], marker='o') ax.plot([0.1, 0.2], [0.1, 0.2], [0.8, 0.6], ls=':', marker='s', mfc='none') t, l, r = get_spiral() ax.plot(t, l, r, color='k') plt.show() ``` -------------------------------- ### Import mpltern and Matplotlib Source: https://mpltern.readthedocs.io/en/latest/_sources/basic_usage.rst.txt Import the necessary libraries to begin using mpltern. This registers the 'ternary' projection. ```python import matplotlib.pyplot as plt import mpltern ``` -------------------------------- ### Setting Ternary Plot Aspect Ratio Source: https://mpltern.readthedocs.io/en/latest/_downloads/081109d37f398f53db66f3bbd9e53685/00.aspect.ipynb Use `ax.set_aspect` to control the aspect ratio of a ternary plot. This example shows setting it to 1.5. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_spiral ax = plt.subplot(projection='ternary') ax.plot(*get_spiral()) ax.set_aspect(1.5) ax.set_tlabel('Top') ax.set_llabel('Left') ax.set_rlabel('Right') plt.show() ``` -------------------------------- ### Import Libraries and Data Source: https://mpltern.readthedocs.io/en/latest/_downloads/a9754b9e965bd1513dff9cab1e73b865/01.style_sheets.ipynb Imports necessary libraries (matplotlib.pyplot) and a sample dataset (get_spiral) for plotting. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_spiral ``` -------------------------------- ### Control Tick Label Rotation Source: https://mpltern.readthedocs.io/en/latest/gallery/axis_and_tick/12.tick_rotation.html Modify tick rotation using `ax.tick_params(labelrotation=...)`. This example shows different rotation options: 'tick', 'axis', and 'horizontal'. ```python import matplotlib.pyplot as plt import mpltern fig = plt.figure(figsize=(10.8, 4.8)) fig.subplots_adjust(left=0.075, right=0.925, wspace=0.25) for i, labelrotation in enumerate(["tick", "axis", "horizontal"]): ax = fig.add_subplot(1, 3, i + 1, projection='ternary') ax.tick_params(labelrotation=labelrotation) ax.set_title(f"labelrotation='{labelrotation}'", pad=36) plt.show() ``` -------------------------------- ### Import Libraries and Generate Data Source: https://mpltern.readthedocs.io/en/latest/_downloads/755f011432021d4601fa0c293adfba27/hexbin.ipynb Imports necessary libraries (numpy, matplotlib, mpltern) and generates sample ternary data using `np.random.dirichlet`. This data is used for creating hexbin plots. ```python import numpy as np import matplotlib.pyplot as plt import mpltern np.random.seed(19680801) t, l, r = np.random.dirichlet(alpha=(2.0, 4.0, 8.0), size=100000).T ``` -------------------------------- ### Plotting on an Arbitrary Triangle Source: https://mpltern.readthedocs.io/en/latest/_downloads/5853751a4cba801ea4f1ce1401ed31f4/02.arbitrary_triangle.ipynb Use this snippet to create a ternary plot with custom corner coordinates. Ensure matplotlib and mpltern are installed. The `get_spiral` function is used here for demonstration purposes. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_spiral corners = ((0.0, 0.0), (0.5, 0.5), (-0.5, 1.0)) ax = plt.subplot(projection='ternary', corners=corners) ax.plot(*get_spiral()) ax.set_tlabel('Top') ax.set_llabel('Left') ax.set_rlabel('Right') ax.grid() plt.show() ``` -------------------------------- ### Adding a Legend to a Ternary Plot Source: https://mpltern.readthedocs.io/en/latest/_downloads/6ca0d2e0b0fd73bb5246b635495e0b86/legend.ipynb This snippet shows how to create a ternary plot and add a legend to it. It uses `numpy` for data generation and `matplotlib.pyplot` with `mpltern` for plotting. Ensure `mpltern` is installed. ```python import numpy as np import matplotlib.pyplot as plt import mpltern ax = plt.subplot(projection="ternary") np.random.seed(19680801) for i in range(4): t, l, r = np.random.dirichlet(alpha=(2.0, 2.0, 2.0), size=10).T ax.scatter(t, l, r, alpha=0.5, label=i) ax.legend() plt.show() ``` -------------------------------- ### Import mpltern and Matplotlib Source: https://mpltern.readthedocs.io/en/latest/basic_usage.html Import the necessary libraries, mpltern and Matplotlib, to begin creating ternary plots. ```python import matplotlib.pyplot as plt import mpltern ``` -------------------------------- ### Set Ternary Axis Label Rotation Mode Source: https://mpltern.readthedocs.io/en/latest/_downloads/f36124de34d49d39108f712ea6bf98eb/01.axis_label_rotation.ipynb Apply different label rotation modes ('axis' or 'horizontal') to ternary plot axes. This example visualizes the effect of each mode on the axis labels. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_spiral pad = 42 t, l, r = get_spiral() fig = plt.figure(figsize=(10.8, 4.8)) fig.subplots_adjust(wspace=0.3) modes = ['axis', 'horizontal'] for i, mode in enumerate(modes): ax = fig.add_subplot(1, 2, i + 1, projection='ternary') ax.plot(t, l, r) ax.set_tlabel('Top') ax.set_llabel('Left') ax.set_rlabel('Right') ax.taxis.set_label_rotation_mode(mode) ax.laxis.set_label_rotation_mode(mode) ax.raxis.set_label_rotation_mode(mode) ax.set_title("label_rotation_mode='{}'".format(mode), pad=pad) plt.show() ``` -------------------------------- ### Replicator Equation Visualization Source: https://mpltern.readthedocs.io/en/latest/_downloads/abfa4b9c1e00efb75b6afa1fc1511bd6/evolutionary_game_theory.ipynb Visualizes the dynamics of the replicator equation using a payoff matrix and ternary plots. Requires matplotlib, numpy, and mpltern. The code calculates fitness, determines the direction of change (d), and plots the results on a ternary diagram with quiver arrows indicating strategy evolution. ```python import matplotlib.pyplot as plt import numpy as np from mpltern.datasets import get_triangular_grid x = np.array(get_triangular_grid(25)) payoff_matrix = [ [0.0, -1.0, 1.0], [1.0, 0.0, -1.0], [-1.0, 1.0, 0.0], ] fitness = payoff_matrix @ x d = (fitness - np.sum(fitness * x, axis=0)) * x norm = np.linalg.norm(d, axis=0) ax = plt.subplot(projection="ternary") ax.tripcolor(*x, norm, cmap="turbo", shading="gouraud", rasterized=True) ax.quiver(*x, *d, scale=5, clip_on=False) ax.set_tlabel("$x_0$") ax.set_llabel("$x_1$") ax.set_rlabel("$x_2$") plt.show() ``` -------------------------------- ### Import Libraries Source: https://mpltern.readthedocs.io/en/latest/gallery/intermediate/01.style_sheets.html Imports necessary libraries for plotting and data retrieval. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_spiral ``` -------------------------------- ### Create TernaryAxes with Custom Sum and Labels Source: https://mpltern.readthedocs.io/en/latest/_sources/basic_usage.rst.txt Create a TernaryAxes with a specified normalization constant (ternary_sum) and set custom labels for the top, left, and right axes. Also adds a grid. ```python ax = plt.subplot(projection="ternary", ternary_sum=100.0) ax.set_tlabel("Top (%)") ax.set_llabel("Left (%)") ax.set_rlabel("Right (%)") ax.grid() plt.show() ``` -------------------------------- ### Set Manual Tick Positions in Ternary Plot Source: https://mpltern.readthedocs.io/en/latest/_downloads/0e540e7d76806b323fbb3aec4f2380e6/30.manual_tick_positions.ipynb Use `set_ticks()` on the respective axis objects (taxis, laxis, raxis) to manually define tick positions. This example plots a spiral and customizes the ticks on all three axes. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_spiral ax = plt.subplot(projection='ternary') ax.plot(*get_spiral()) ax.grid() ax.set_tlabel('Top') ax.set_llabel('Left') ax.set_rlabel('Right') # Specify tick positions manually. ax.taxis.set_ticks([0.2, 0.4, 0.6, 0.8, 1.0]) ax.laxis.set_ticks([0.2, 0.4, 0.6, 0.8, 1.0]) ax.raxis.set_ticks([0.2, 0.4, 0.6, 0.8, 1.0]) plt.show() ``` -------------------------------- ### Plotting Arrows on Ternary Diagram Source: https://mpltern.readthedocs.io/en/latest/_downloads/0980e039de204273861bea5734d43435/08.quiver.ipynb Plots a 2D field of arrows on a ternary diagram. The sum of the three components (dt, dl, dr) must be zero. This example shows plotting with default arrow length and with a specified length. ```python import numpy as np import matplotlib.pyplot as plt from mpltern.datasets import get_triangular_grid t, l, r = get_triangular_grid() # Arrows. The sum of the three must be zero. dt = 1.0 / 3.0 - t dl = 1.0 / 3.0 - l dr = 1.0 / 3.0 - r length = np.sqrt(dt ** 2 + dl ** 2 + dr ** 2) fig = plt.figure(figsize=(10.8, 4.8)) fig.subplots_adjust(left=0.075, right=0.85, wspace=0.3) ax = fig.add_subplot(121, projection='ternary') pc = ax.quiver(t, l, r, dt, dl, dr) ax = fig.add_subplot(122, projection='ternary') pc = ax.quiver(t, l, r, dt, dl, dr, length) cax = ax.inset_axes([1.05, 0.1, 0.05, 0.9], transform=ax.transAxes) colorbar = fig.colorbar(pc, cax=cax) colorbar.set_label('Length', rotation=270, va='baseline') plt.show() ``` -------------------------------- ### Mpltern Logo Generation Functions Source: https://mpltern.readthedocs.io/en/latest/_sources/gallery/miscellaneous/00.logos.rst.txt Defines helper functions to create the mpltern logo, including functions for creating axes with ternary spans and axes for text rendering. It also includes the main function to generate the full figure. ```Python import matplotlib.pyplot as plt import matplotlib.font_manager from matplotlib.patches import PathPatch from matplotlib.text import TextPath import matplotlib.transforms as mtrans import mpltern # noqa: F401 MPL_BLUE = '#11557c' def get_font_properties(): return matplotlib.font_manager.FontProperties(weight='bold') def create_icon_axes(fig, ax_position, lw_grid, lw_border): """ Create a ternary axes containing the mpltern span plot. Parameters ---------- fig : matplotlib.figure.Figure The figure to draw into. ax_position : (float, float, float, float) The position of the created Axes in figure coordinates as (x, y, width, height). lw_grid : float The linewidth of the grid. lw_border : float The linewidth of the Axes border. Returns ------- ax : matplotlib.axes.Axes The created Axes. """ with plt.rc_context({'axes.edgecolor': MPL_BLUE, 'axes.linewidth': lw_border}): ax = fig.add_axes(ax_position, projection='ternary') ax.axtspan(0.4, 0.6, color='C0', alpha=0.6) ax.axlspan(0.4, 0.6, color='C1', alpha=0.6) ax.axrspan(0.4, 0.6, color='C2', alpha=0.6) ax.tick_params( tick1On=False, tick2On=False, label1On=False, label2On=False) ax.grid(lw=lw_grid, color='0.9') # the actual visible background - extends a bit beyond the axis ax.fill( (1.04, -0.02, -0.02), (-0.02, 1.04, -0.02), (-0.02, -0.02, 1.04), facecolor='white', zorder=0, clip_on=False, in_layout=False) return ax def create_text_axes(fig, height_px): """Create an Axes in *fig* that contains 'mpltern' as Text.""" ax = fig.add_axes((0, 0, 1, 1)) ax.set_aspect("equal") ax.set_axis_off() path = TextPath((0, 0), "mpl tern", size=height_px * 0.8, prop=get_font_properties()) angle = 4.25 # degrees trans = mtrans.Affine2D().skew_deg(angle, 0) patch = PathPatch(path, transform=trans + ax.transData, color=MPL_BLUE, lw=0) ax.add_patch(patch) ax.autoscale() def make_logo(height_px, lw_grid, lw_border, with_text=False): """ Create a full figure with the mpltern logo. Parameters ---------- height_px : int Height of the figure in pixel. lw_grid : float The linewidth of the grid. lw_border : float The linewidth of icon border. with_text : bool Whether to draw only the icon or to include 'mpltern' as text. """ dpi = 100 height = height_px / dpi figsize = (5 * height, height) if with_text else (height, height) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) if with_text: create_text_axes(fig, height_px) ax_pos = (0.395, 0.12, .17, 0.75) if with_text else (0.1, 0.1, 0.8, 0.8) ax = create_icon_axes(fig, ax_pos, lw_grid, lw_border) return fig, ax ``` -------------------------------- ### Generate Mpltern Logo with Text Source: https://mpltern.readthedocs.io/en/latest/_downloads/fa8c7f59a477102d318377608aa3d48c/00.logos.ipynb Generates a large Mpltern logo that includes the 'mpltern' text. This version is used on the Mpltern website. Ensure `plt.show()` is called to display the figure. ```python make_logo(height_px=110, lw_grid=0.5, lw_border=1, with_text=True) plt.show() ``` -------------------------------- ### Create Ternary Axes with Custom Sum and Labels Source: https://mpltern.readthedocs.io/en/latest/basic_usage.html Create a ternary axes with a custom normalization constant (ternary_sum) and set custom labels for the top, left, and right axes. A grid is also added. ```python ax = plt.subplot(projection="ternary", ternary_sum=100.0) ax.set_tlabel("Top (%)") ax.set_llabel("Left (%)") ax.set_rlabel("Right (%)") ax.grid() plt.show() ``` -------------------------------- ### Generate Mpltern Logo Icon Source: https://mpltern.readthedocs.io/en/latest/_downloads/fa8c7f59a477102d318377608aa3d48c/00.logos.ipynb This function creates a ternary axes with Mpltern's logo icon. It sets up the axes, adds spans, ticks, grid, and a background fill. Use this for generating the core icon. ```python import matplotlib.pyplot as plt import matplotlib.font_manager from matplotlib.patches import PathPatch from matplotlib.text import TextPath import matplotlib.transforms as mtrans import mpltern # noqa: F401 MPL_BLUE = '#11557c' def get_font_properties(): return matplotlib.font_manager.FontProperties(weight='bold') def create_icon_axes(fig, ax_position, lw_grid, lw_border): """ Create a ternary axes containing the mpltern span plot. Parameters ---------- fig : matplotlib.figure.Figure The figure to draw into. ax_position : (float, float, float, float) The position of the created Axes in figure coordinates as (x, y, width, height). lw_grid : float The linewidth of the grid. lw_border : float The linewidth of the Axes border. Returns ------- ax : matplotlib.axes.Axes The created Axes. """ with plt.rc_context({'axes.edgecolor': MPL_BLUE, 'axes.linewidth': lw_border}): ax = fig.add_axes(ax_position, projection='ternary') ax.axtspan(0.4, 0.6, color='C0', alpha=0.6) ax.axlspan(0.4, 0.6, color='C1', alpha=0.6) ax.axrspan(0.4, 0.6, color='C2', alpha=0.6) ax.tick_params( tick1On=False, tick2On=False, label1On=False, label2On=False) ax.grid(lw=lw_grid, color='0.9') # the actual visible background - extends a bit beyond the axis ax.fill( (1.04, -0.02, -0.02), (-0.02, 1.04, -0.02), (-0.02, -0.02, 1.04), facecolor='white', zorder=0, clip_on=False, in_layout=False) return ax def create_text_axes(fig, height_px): """Create an Axes in *fig* that contains 'mpltern' as Text.""" ax = fig.add_axes((0, 0, 1, 1)) ax.set_aspect("equal") ax.set_axis_off() path = TextPath((0, 0), "mpl tern", size=height_px * 0.8, prop=get_font_properties()) angle = 4.25 # degrees trans = mtrans.Affine2D().skew_deg(angle, 0) patch = PathPatch(path, transform=trans + ax.transData, color=MPL_BLUE, lw=0) ax.add_patch(patch) ax.autoscale() def make_logo(height_px, lw_grid, lw_border, with_text=False): """ Create a full figure with the mpltern logo. Parameters ---------- height_px : int Height of the figure in pixel. lw_grid : float The linewidth of the grid. lw_border : float The linewidth of icon border. with_text : bool Whether to draw only the icon or to include 'mpltern' as text. """ dpi = 100 height = height_px / dpi figsize = (5 * height, height) if with_text else (height, height) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) if with_text: create_text_axes(fig, height_px) ax_pos = (0.395, 0.12, .17, 0.75) if with_text else (0.1, 0.1, 0.8, 0.8) ax = create_icon_axes(fig, ax_pos, lw_grid, lw_border) return fig, ax ``` -------------------------------- ### Generate Small Mpltern Logo Source: https://mpltern.readthedocs.io/en/latest/_downloads/fa8c7f59a477102d318377608aa3d48c/00.logos.ipynb Generates a small Mpltern logo icon, suitable for favicons or small UI elements. The line widths are scaled down accordingly. ```python make_logo(height_px=32, lw_grid=0.3, lw_border=0.3) ``` -------------------------------- ### Replicator Equation Visualization Source: https://mpltern.readthedocs.io/en/latest/gallery/miscellaneous/evolutionary_game_theory.html Visualizes the replicator equation using a ternary plot. This snippet requires matplotlib and numpy. It calculates fitness based on a payoff matrix and displays the evolution of strategies. ```python import matplotlib.pyplot as plt import numpy as np from mpltern.datasets import get_triangular_grid x = np.array(get_triangular_grid(25)) payoff_matrix = [ [0.0, -1.0, 1.0], [1.0, 0.0, -1.0], [-1.0, 1.0, 0.0], ] fitness = payoff_matrix @ x d = (fitness - np.sum(fitness * x, axis=0)) * x norm = np.linalg.norm(d, axis=0) ax = plt.subplot(projection="ternary") ax.tripcolor(*x, norm, cmap="turbo", shading="gouraud", rasterized=True) ax.quiver(*x, *d, scale=5, clip_on=False) ax.set_tlabel("$x_0$") ax.set_llabel("$x_1$") ax.set_rlabel("$x_2$") plt.show() ``` -------------------------------- ### Plotting with Custom Ternary Sum Source: https://mpltern.readthedocs.io/en/latest/_downloads/b96d93b7134470913bc470b599eb8a63/04.normalization.ipynb Demonstrates how to create a ternary plot with a custom normalization sum (e.g., 100.0). The data is automatically normalized according to the specified `ternary_sum`. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_spiral fig = plt.figure() ax = fig.add_subplot(projection='ternary', ternary_sum=100.0) t, l, r = get_spiral() ax.plot(t, l, r) # Data are automatically normalized by ``ternary_sum``. plt.show() ``` -------------------------------- ### Basic TriBin Plot Source: https://mpltern.readthedocs.io/en/latest/_downloads/91b975661f3214a0e9e6a98542b01c7b/tribin.ipynb Creates a basic TriBin plot using default settings. It's recommended to set 'edgecolors="none"' to avoid overlapping visual artifacts with small triangles. ```python ax = plt.subplot(projection="ternary") # If "edgecolors=face" (default), small triangles look overlapping. ax.tribin(t, l, r, edgecolors="none") plt.show() ``` -------------------------------- ### mpltern.ternary.TernaryAxes.hexbin Source: https://mpltern.readthedocs.io/en/latest/_sources/api.rst.txt Creates a hexagonal binning plot. ```APIDOC ## mpltern.ternary.TernaryAxes.hexbin ### Description Creates a hexagonal binning plot. ### Method (Method details not provided in source) ### Parameters (Parameter details not provided in source) ### Request Example (Request example not provided in source) ### Response (Response details not provided in source) ``` -------------------------------- ### mpltern.ternary.TernaryAxes.tribin Source: https://mpltern.readthedocs.io/en/latest/_sources/api.rst.txt Creates a triangular binning plot. ```APIDOC ## mpltern.ternary.TernaryAxes.tribin ### Description Creates a triangular binning plot. ### Method (Method details not provided in source) ### Parameters (Parameter details not provided in source) ### Request Example (Request example not provided in source) ### Response (Response details not provided in source) ``` -------------------------------- ### Plotting Lines and Regions with Ternary Transforms Source: https://mpltern.readthedocs.io/en/latest/_downloads/244a00f379e58c9228d3cf25c43a1e17/01.ticks.ipynb Demonstrates plotting lines and filling regions along the t, l, and r axes using their respective transforms. This is useful for visualizing data ranges or specific conditions on a ternary plot. ```python import matplotlib.pyplot as plt import mpltern # noqa: F401 ax = plt.subplot(projection="ternary", ternary_sum=100.0) x0 = 0.0 x1 = 100.0 ax.plot([x0, x1], [0.5, 0.5], transform=ax.get_taxis_transform()) ax.plot([x0, x1], [0.5, 0.5], transform=ax.get_laxis_transform()) ax.plot([x0, x1], [0.5, 0.5], transform=ax.get_raxis_transform()) y = [0.4, 0.6] ax.fill_betweenx(y, x0, x1, alpha=0.2, transform=ax.get_taxis_transform()) ax.fill_betweenx(y, x0, x1, alpha=0.2, transform=ax.get_laxis_transform()) ax.fill_betweenx(y, x0, x1, alpha=0.2, transform=ax.get_raxis_transform()) plt.show() ``` -------------------------------- ### Plotting a Triangular Grid Source: https://mpltern.readthedocs.io/en/latest/_downloads/de839b78b8414ca90e384ae5258d2883/11.triangular_grid.ipynb Generates and plots a triangular grid. Use this to visualize data distributed across three components. ```python import matplotlib.pyplot as plt from mpltern.datasets import get_triangular_grid t, l, r = get_triangular_grid() fig = plt.figure(figsize=(10.8, 4.8)) fig.subplots_adjust(wspace=0.3) ax = fig.add_subplot(121, projection='ternary') ax.triplot(t, l, r) ax = fig.add_subplot(122, projection='ternary') ax.triplot(t, l, r, marker='o') plt.show() ``` -------------------------------- ### Basic Hexbin Plot on Ternary Diagram Source: https://mpltern.readthedocs.io/en/latest/_downloads/755f011432021d4601fa0c293adfba27/hexbin.ipynb Creates a basic hexbin plot on a ternary diagram using `ax.hexbin`. The `edgecolors='none'` argument is used to prevent overlapping appearance of small hexagons. ```python ax = plt.subplot(projection="ternary") # If "edgecolors=face" (default), small hexagons look overlapping. ax.hexbin(t, l, r, edgecolors="none") plt.show() ``` -------------------------------- ### Hexbin and Scatter Plot on Ternary Diagram Source: https://mpltern.readthedocs.io/en/latest/_downloads/92412ddc0eefd06ab8f60f2963f0e94d/with_scatter.ipynb Use this snippet to create a ternary plot showing a hexbin density distribution overlaid with individual scatter points. Requires `numpy`, `matplotlib`, and `mpltern`. Ensure data is generated using `np.random.dirichlet` or similar. ```python import numpy as np import matplotlib.pyplot as plt import mpltern np.random.seed(19680801) t, l, r = np.random.dirichlet(alpha=(2.0, 2.0, 2.0), size=100).T fig = plt.figure(figsize=(10.8, 4.8)) fig.subplots_adjust(left=0.075, right=0.85, wspace=0.3) ax = fig.add_subplot(1, 2, 1, projection="ternary") ax.scatter(t, l, r, color="C3", marker="x") pc = ax.hexbin(t, l, r, gridsize=10, edgecolors="k", alpha=0.5, zorder=0.0) ax.set_title("hexbin") cax = ax.inset_axes([1.05, 0.1, 0.05, 0.9], transform=ax.transAxes) colorbar = fig.colorbar(pc, cax=cax) colorbar.set_label("Count", rotation=270, va="baseline") ax = fig.add_subplot(1, 2, 2, projection="ternary") ax.scatter(t, l, r, color="C3", marker="x") pc = ax.tribin(t, l, r, gridsize=10, edgecolors="k", alpha=0.5, zorder=0.0) ax.set_title("tribin") cax = ax.inset_axes([1.05, 0.1, 0.05, 0.9], transform=ax.transAxes) colorbar = fig.colorbar(pc, cax=cax) colorbar.set_label("Count", rotation=270, va="baseline") plt.show() ``` -------------------------------- ### mpltern.ternary.TernaryAxes.axlline Source: https://mpltern.readthedocs.io/en/latest/_sources/api.rst.txt Draws a line along the left axis. ```APIDOC ## mpltern.ternary.TernaryAxes.axlline ### Description Draws a line along the left axis. ### Method (Method details not provided in source) ### Parameters (Parameter details not provided in source) ### Request Example (Request example not provided in source) ### Response (Response details not provided in source) ``` -------------------------------- ### Plot Data on a Ternary Axes Source: https://mpltern.readthedocs.io/en/latest/basic_usage.html Demonstrates how to plot data points (t, l, r) on a ternary axes using the ax.plot method, similar to standard Matplotlib plotting. ```python from mpltern.datasets import get_spiral ax = plt.subplot(projection="ternary") t, l, r = get_spiral() # t: [0.33333333 0.33357906 0.33430414 ...] # l: [0.33333333 0.33455407 0.33543547 ...] # r: [0.33333333 0.33186687 0.33026039 ...] ax.plot(t, l, r) plt.show() ``` -------------------------------- ### Creating an Inset Ternary Plot Source: https://mpltern.readthedocs.io/en/latest/_downloads/862273d3786ea479e2550d8a5cefcd48/99.inset.ipynb This snippet demonstrates how to create a main ternary plot and then add an inset ternary plot. It includes setting up random data, plotting scatter points on both axes, and defining the region for the inset. The inset axes are created using `fig.add_axes` with specified figure coordinates and their plotting range is limited using `set_ternary_min`. ```python import numpy as np import matplotlib.pyplot as plt import mpltern np.random.seed(seed=19) t0, l0, r0 = np.random.dirichlet(alpha=(2.0, 2.0, 2.0), size=100).T np.random.seed(seed=68) t1, l1, r1 = np.random.dirichlet(alpha=(2.0, 2.0, 2.0), size=100).T fig = plt.figure() fig.subplots_adjust(left=-0.1) ax = fig.add_subplot(projection="ternary") ax.scatter(t0, l0, r0, alpha=0.5) ax.scatter(t1, l1, r1, alpha=0.5) # Plot the triangle region for the inset. ax.fill([0.4, 0.3, 0.3], [0.3, 0.4, 0.3], [0.3, 0.3, 0.4], fc="none", ec="k") # Create a new `TernaryAxes` for the inset with specifying a rectangle in the # figure coordinates. axins = fig.add_axes([0.625, 0.525, 0.30, 0.30], projection="ternary") # Limit the ploting range to be consistent with the above plotted triangle. axins.set_ternary_min(0.3, 0.3, 0.3) axins.scatter(t0, l0, r0, alpha=0.5) axins.scatter(t1, l1, r1, alpha=0.5) plt.show() ``` -------------------------------- ### TriBin Plot with Logarithmic Binning Source: https://mpltern.readthedocs.io/en/latest/_downloads/91b975661f3214a0e9e6a98542b01c7b/tribin.ipynb Generates a TriBin plot with logarithmic binning. This is useful for visualizing data with a wide range of densities. ```python ax = plt.subplot(projection="ternary") ax.tribin(t, l, r, bins="log", edgecolors="none") plt.show() ``` -------------------------------- ### Plotting Dirichlet PDFs Source: https://mpltern.readthedocs.io/en/latest/_sources/gallery/miscellaneous/dirichlet_pdf.rst.txt Generates and plots the probability density functions for different Dirichlet distributions on ternary diagrams. This is useful for visualizing how the shape of the distribution changes with different alpha parameters. ```Python import matplotlib.pyplot as plt from mpltern.datasets import get_dirichlet_pdfs fig = plt.figure(figsize=(10.8, 8.8)) fig.subplots_adjust( left=0.1, right=0.9, bottom=0.1, top=0.9, wspace=0.5, hspace=0.5, ) alphas = ((1.5, 1.5, 1.5), (5.0, 5.0, 5.0), (1.0, 2.0, 2.0), (2.0, 4.0, 8.0)) for i, alpha in enumerate(alphas): ax = fig.add_subplot(2, 2, i + 1, projection="ternary") t, l, r, v = get_dirichlet_pdfs(n=61, alpha=alpha) cmap = "Blues" shading = "gouraud" cs = ax.tripcolor(t, l, r, v, cmap=cmap, shading=shading, rasterized=True) ax.tricontour(t, l, r, v, colors="k", linewidths=0.5) ax.set_tlabel("$x_1$") ax.set_llabel("$x_2$") ax.set_rlabel("$x_3$") ax.taxis.set_label_position("tick1") ax.laxis.set_label_position("tick1") ax.raxis.set_label_position("tick1") ax.set_title("${\mathbf{\alpha}}$ = " + str(alpha)) cax = ax.inset_axes([1.05, 0.1, 0.05, 0.9], transform=ax.transAxes) colorbar = fig.colorbar(cs, cax=cax) colorbar.set_label("PDF", rotation=270, va="baseline") plt.show() ``` -------------------------------- ### Hexbin Plot with Logarithmic Binning Source: https://mpltern.readthedocs.io/en/latest/_downloads/755f011432021d4601fa0c293adfba27/hexbin.ipynb Generates a hexbin plot on a ternary diagram with logarithmic binning applied. This is useful for visualizing data with a wide range of counts per bin. ```python ax = plt.subplot(projection="ternary") ax.hexbin(t, l, r, bins="log", edgecolors="none") plt.show() ```