typhon.plots

This module provides functions related to plot or to plot data.

typhon.plots.cmap2act(cmap, filename=None, N=None)[source]

Export colormap to Adobe Color Table file.

Parameters:
  • cmap (str) – Colormap name.
  • filename (str) – Optional filename. Default: cmap + ‘.cpt’
  • N (int) – Number of colors.
typhon.plots.cmap2c3g(cmap, filename=None, N=None)[source]

Export colormap ass CSS3 gradient.

Parameters:
  • cmap (str) – Colormap name.
  • filename (str) – Optional filename. Default: cmap + ‘.cpt’
  • N (int) – Number of colors.
typhon.plots.cmap2cpt(cmap, filename=None, N=None)[source]

Export colormap to cpt file.

Parameters:
  • cmap (str) – Colormap name.
  • filename (str) – Optional filename. Default: cmap + ‘.cpt’
  • N (int) – Number of colors.
typhon.plots.cmap2ggr(cmap, filename=None, N=None)[source]

Export colormap as GIMP gradient.

Parameters:
  • cmap (str) – Colormap name.
  • filename (str) – Optional filename. Default: cmap + ‘.cpt’
  • N (int) – Number of colors.
typhon.plots.cmap2txt(cmap, filename=None, N=None, comments='%')[source]

Export colormap to txt file.

Parameters:
  • cmap (str) – Colormap name.
  • filename (str) – Optional filename. Default: cmap + ‘.txt’
  • N (int) – Number of colors.
  • comments (str) – Character to start comments with.
typhon.plots.cmap_from_act(file, name=None)[source]

Import colormap from Adobe Color Table file.

Parameters:
  • file (str) – Path to act file.
  • name (str) – Colormap name. Defaults to filename without extension.
Returns:

LinearSegmentedColormap.

typhon.plots.cmap_from_txt(file, name=None, N=-1, comments='%')[source]

Import colormap from txt file.

Reads colormap data (RGB/RGBA) from an ASCII file. Values have to be given in [0, 1] range.

Parameters:
  • file (str) – Path to txt file.
  • name (str) – Colormap name. Defaults to filename without extension.
  • N (int) – Number of colors. -1 means all colors (i.e., the complete file).
  • comments (str) – Character to start comments with.
Returns:

LinearSegmentedColormap.

typhon.plots.colors2cmap(*args, name=None)[source]

Create a colormap from a list of given colors.

Parameters:
  • *args – Arbitrary number of colors (Named color, HEX or RGB).
  • name (str) – Name with which the colormap is registered.
Returns:

LinearSegmentedColormap.

Examples

>>> colors2cmap('darkorange', 'white', 'darkgreen', name='test')
typhon.plots.figsize(w, portrait=False)[source]

Return a figure size matching the golden ratio.

This function takes a figure width and returns a tuple representing width and height in the golden ratio. Results can be returned for portrait orientation.

Parameters:
  • w (float) – Figure width.
  • portrait (bool) – Return size for portrait format.
Returns:

Figure width and size.

Return type:

tuple

Examples

>>> import typhon.plots
>>> typhon.plots.figsize(1)
(1, 0.61803398874989479)
>>> typhon.plots.figsize(1, portrait=True)
(1, 1.6180339887498949)
typhon.plots.get_available_styles()[source]

Return list of names of all styles shipped with typhon.

Returns:List of available styles.
Return type:list[str]
typhon.plots.get_subplot_arrangement(n)[source]

Get efficient (nrow, ncol) for n subplots

If we want to put n subplots in a square-ish/rectangular arrangement, how should we arrange them?

Returns (⌈√n⌉, ‖√n‖)

typhon.plots.heatmap(x, y, bins=20, bisectrix=True, ax=None, **kwargs)[source]

Plot a heatmap of two data arrays.

This function is a simple wrapper for plt.hist2d().

Parameters:
  • x (np.ndarray) – x data.
  • y (np.ndarray) – y data.
  • bins (int | [int, int] | array_like | [array, array]) –

    The bin specification:

    • If int, the number of bins for the two dimensions (nx=ny=bins).
    • If [int, int], the number of bins in each dimension (nx, ny = bins).
    • If array_like, the bin edges for the two dimensions (x_edges=y_edges=bins).
    • If [array, array], the bin edges in each dimension (x_edges, y_edges = bins).

    The default value is 20.

  • bisectrix (bool) – Toggle drawing of the bisectrix.
  • ax (AxesSubplot, optional) – Axes to plot in.
  • **kwargs – Additional keyword arguments passed to matplotlib.pyplot.hist2d().
Returns:

AxesImage.

Examples:

import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import heatmap


x = np.random.randn(500)
y = x + np.random.randn(x.size)

fig, ax = plt.subplots()
heatmap(x, y, ax=ax)

plt.show()

(Source code, png, hires.png, pdf)

_images/typhon-plots-1.png
typhon.plots.mpl_colors(cmap=None, N=None)[source]

Return a list of RGB values.

Parameters:
  • cmap (str) – Name of a registered colormap.
  • N (int) – Number of colors to return. If None use the number of colors defined in the colormap.
Returns:

Array with RGB and alpha values.

Return type:

np.array

Examples

>>> mpl_colors('viridis', 5)
array([[ 0.267004,  0.004874,  0.329415,  1.      ],
    [ 0.229739,  0.322361,  0.545706,  1.      ],
    [ 0.127568,  0.566949,  0.550556,  1.      ],
    [ 0.369214,  0.788888,  0.382914,  1.      ],
    [ 0.993248,  0.906157,  0.143936,  1.      ]])
typhon.plots.plot_distribution_as_percentiles(ax, x, y, nbins=10, bins=None, ptiles=(5, 25, 50, 75, 95), linestyles=(':', '--', '-', '--', ':'), ptile_to_legend=True, label=None, **kwargs)[source]

Plot the distribution of y vs. x as percentiles.

Bin y-data according to x-data (using typhon.math.stats.bin()). Then, within each bin, show the distribution by plotting percentiles.

Parameters:
  • ax (AxesSubplot) – matplotlib axes to plot into
  • x (ndarray) – data for x-axis
  • y (ndarray) – data for y-axis
  • nbins (int) – Number of bins to use for dividing the x-data.
  • bins (ndarray) – Specific bins to use for dividing the x-data. Supersedes nbins.
  • ptiles (ndarray) – Percentiles to visualise.
  • linestyles (List[str]) – List of linestyles corresponding to percentiles
  • ptile_to_legend (bool) – True: Add a label to each percentile. False: Only add a legend to the median.
  • label (str or None) – Label to use in legend.
  • **kwargs – Remaining arguments passed to AxesSubplot.plot(). You probably want to pass at least color.
typhon.plots.scatter_density_plot_matrix(M=None, hist_kw={}, hexbin_kw={'cmap': 'viridis', 'mincnt': 1}, plot_dist_kw={'linewidth': 1.5, 'ptiles': [5, 25, 50, 75, 95], 'linestyles': [':', '--', '-', '--', ':'], 'color': 'tan'}, ranges={}, units=None, **kwargs)[source]

Plot a scatter density plot matrix

Like a scatter plot matrix but rather than every axes containing a scatter plot of M[i] vs. M[j], it contains a 2-D histogram along with the distribution as percentiles. The 2-D histogram is created using hexbin rather than hist2d, because hexagonal bins are a more appropriate. For example, see http://www.meccanismocomplesso.org/en/hexagonal-binning/

On top of the 2-D histogram, shows the distribution using func:plot_distribution_as_percentiles.

Plots regular 1-D histograms in the diagonals.

There are three ways to pass the data:

  1. As a structured ndarray. This is the preferred way. The fieldnames will be used for the axes and order is preserved. Each field in the dtype must be scalar (0-d) and numerical.
  2. As keyword arguments. All extra keyword arguments will be taken as variables. They must all be 1-D ndarrays of numerical dtype, and they must all have the same size. Order is preserve from Python 3.6 only.
  3. As a regular 2-D numerical ndarray of shape [N × p]. In this case, the innermost dimension will be taken as the quantities to be plotted. There is no axes labelling.
Parameters:
  • M (np.ndarray) – ndarray. If structured, the fieldnames will be used as the variables to be plotted against each other. Each field in the structured array shall be 0-dimensional and of a numerical dtype. If not structured, interpreted as 2-D array and the axes will be unlabelled. You should pass either this argument, or additional keyworad arguments (see below).
  • hist_kw (Mapping) – Keyword arguments to pass to hist for diagonals.
  • hexbin_kw (Mapping) – Keyword arguments to pass to each call of hexbin.
  • plot_dist_kw (Mapping) – Keyword arguments to pass to each call of func:plot_distribution_as_percentiles.
  • ranges (Mapping[str, Tuple[Real, Real]]) – For each field in M, can pass a range. If provided, this range will be passed on to hist and hexbin.
  • units (Mapping[str, str]) – Unit strings for each of the quantities. Optional. If not passed, no unit is shown in the graph, unless the quantities to be plotted are pint quantity objects.

If not passing M, you can instead pass keyword arguments referring to the different fields to be plotted. In this case, each keyword argument should be a 1-dimensional ndarray with a numeric dtype. If you use Python 3.6 or later, the order of the keyword arguments should be preserved.

Returns:
Figure object created.
You will still want to use subplots_adjust, suptitle, perhaps add a colourbar, and other things.
Return type:f (matplotlib.figure.Figure)

Examples:

import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import scatter_density_plot_matrix

x = 5*np.random.randn(5000)
y = x + 10*np.random.randn(x.size)
z = y**2 + x**2 + 20*np.random.randn(x.size)

scatter_density_plot_matrix(
    x=x, y=y, z=z,
    hexbin_kw={"mincnt": 1, "cmap": "viridis", "gridsize": 20},
    units=dict(x="romans", y="knights", z="rabbits"))

plt.show()

(Source code, png, hires.png, pdf)

_images/typhon-plots-2.png
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import scatter_density_plot_matrix

M = np.zeros(shape=(10000,),
             dtype="f,f,f,f")
M["f0"] = np.random.randn(M.size)
M["f1"] = np.random.randn(M.size) + M["f0"]
M["f2"] = 2*np.random.randn(M.size) + M["f0"]*M["f1"]
M["f3"] = M["f0"] + M["f1"] + M["f2"] + 0.5*np.random.randn(M.size)

scatter_density_plot_matrix(M,
    hexbin_kw={"mincnt": 1, "cmap": "viridis", "gridsize": 20})

plt.show()

(Source code, png, hires.png, pdf)

_images/typhon-plots-3.png
typhon.plots.styles(name)[source]

Return absolute path to typhon stylesheet.

Matplotlib stylesheets can be passed via their full path. This function takes a style name and returns the absolute path to the typhon stylesheet.

Parameters:name (str) – Style name.
Returns:Absolute path to stylesheet.
Return type:str

Example

Use typhon style for matplotlib plots.

>>> import matplotlib.pyplot as plt
>>> plt.style.use(styles('typhon'))

Typhon style sheet

# -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import typhon.plots


def simple_plot(style, stylename, **kwargs):
    """Generate a simple plot using a given matplotlib style."""
    plt.style.use('classic')
    plt.style.use(style)

    x = np.linspace(0, 2*np.pi, 20)

    fig, ax = plt.subplots()
    for s in np.linspace(0, np.pi, 10):
        ax.plot(x, np.sin(x+s),
                label=r'$\Delta\omega = {:.2f}$'.format(s),
                marker='.',
                **kwargs
                )
    ax.set_ylabel('y-axis')
    ax.set_xlabel('x-axis')
    ax.set_title(stylename)
    ax.legend()

# Create plot using default styles.
simple_plot('classic', 'classic')

# Create a plot for each available typhon style.
for style in typhon.plots.get_available_styles():
    simple_plot(typhon.plots.styles(style), style)

plt.show()

(Source code)