physt.plotting package

Submodules

physt.plotting.ascii module

ASCII plots (experimental).

The plots are printed directly to standard output.

physt.plotting.ascii.FULL_SQUARE_CHAR = '█'

Character used for horizontal bar plots.

physt.plotting.ascii.SHADING_CHARS = ' ░▒▓█'

Characters used for shading in the ASCII map.

physt.plotting.ascii.hbar(h1: Histogram1D, *, max_width: int | None = None, show_values: bool = False, show_labels: bool = False, color: str | None = None, label_width: int = 10) None

Horizontal bar plot in block characters.

Parameters:
  • h1 – Histogram to plot.

  • max_width – Width of the bars (including labels and values). By default, the width of the terminal minus one.

  • show_values – Whether to show values right of the bars.

  • show_labels – Whether to show bin labels left of the bars.

  • label_width – Width of the label field (if shown).

  • color – Color of the bars.

physt.plotting.ascii.map(h2: Histogram2D, *, use_color: Optional[bool] = None, **kwargs) None

Heat map.

Depending on the color system, it uses either block characters or shades from the colormap.

physt.plotting.common module

Functions that are shared by several (all) plotting backends.

class physt.plotting.common.TimeTickHandler(level: str | None = None)

Bases: object

Callable that creates ticks and labels corresponding to “sane” time values.

Note: This class is very experimental and subject to change or disappear.

LEVELS = {'day': 86400, 'hour': 3600, 'min': 60, 'sec': 1}
classmethod deduce_level(min_: float, max_: float) TimeTickHandler.LevelType

Determine the level of the tick handler from the histogram range.

format_time_ticks(ticks: List[float], level: LevelType) List[str]
get_time_ticks(h1: Histogram1D, level: LevelType, min_: float, max_: float) List[float]

Get ticks for a given level.

classmethod parse_level(value: LevelType | float | str | timedelta) TimeTickHandler.LevelType

Parse the level from any of the supported types.

classmethod split_hms(value: float) Tuple[bool, int, int, int | float]

Split the time value into sign, hours, minutes, seconds

physt.plotting.common.check_ndim(ndim: int | Tuple[int, ...]) Callable[[Callable], Callable]

Decorator checking proper histogram dimension.

Parameters:

ndim (The required dimensionality/ies of the histogram.)

physt.plotting.common.get_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) np.ndarray

Get histogram data based on plotting parameters.

Parameters:
  • density (Whether to divide bin contents by bin size)

  • cumulative (Whether to return cumulative sums instead of individual)

  • flatten (Whether to flatten multidimensional bins)

physt.plotting.common.get_err_data(histogram: HistogramBase, density: bool = False, cumulative: bool = False, flatten: bool = False) np.ndarray

Get histogram error data based on plotting parameters.

Parameters:
  • density (Whether to divide bin contents by bin size)

  • cumulative (Whether to return cumulative sums instead of individual)

  • flatten (Whether to flatten multidimensional bins)

physt.plotting.common.get_value_format(value_format: Callable[[float], str] | str | None) Callable[[float], str]

Create a formatting function from a generic value_format argument.

Parameters:

value_format (A formatting function or a string.)

physt.plotting.common.pop_kwargs_with_prefix(prefix: str, kwargs: Dict[str, Any]) Dict[str, Any]

Pop all items from a dictionary that have keys beginning with a prefix.

Parameters:
  • prefix (The prefix to match.)

  • kwargs (The dictionary to be modified.)

Returns:

  • kwargs (Items popped from the original directory, with prefix removed.)

  • Note that the function modifies the original dictionary.

physt.plotting.folium module

Plotting inside maps with folium.

Very experimental!

physt.plotting.folium.geo_map(h2: Histogram2D, *, map: Map | None = None, tiles: str | None = 'cartodb positron', cmap='wk', alpha: float = 0.5, lw=1, fit_bounds: bool | None = None, layer_name: str | None = None) Map

Show rectangular grid over a map.

Parameters:
  • h2 (A histogram of coordinates (in degrees: latitude, longitude))

  • map (The map to insert the histogram into)

Returns:

map

Return type:

folium.folium.Map

physt.plotting.matplotlib module

Matplotlib backend for plotting in physt.

This module contains several plotting functions and a lot of underscored helper functions. User is expected to use only the former ones.

Plot functions for 1D histograms - bar - scatter - fill - line - step

Plot functions for 2D histograms - map - image - bar3d - polar_map - surface_map - globe_map (for DirectionalHistogram) - cylinder_map (for CylinderSurfaceHistogram)

Each plotting method supports many parameters. These are quite common and very often corresponding to a matplotlib parameter of a same name. The very general keyword argument dict is sequentially forwarded to plotting helper functions that do part of the plotting job and popped of the used parameters.

physt.plotting.matplotlib.bar(h1: Histogram1D, ax: Axes, *, errors: bool = False, **kwargs)

Bar plot of 1D histograms.

physt.plotting.matplotlib.bar3d(h2: Histogram2D, ax: Axes3D, *, density: bool = False, **kwargs)

Plot of 2D histograms as 3D boxes.

physt.plotting.matplotlib.cylinder_map(hist: Histogram2D | CylindricalSurfaceHistogram, ax: Axes3D, *, show_zero: bool = True, **kwargs) None

Heat map plotted on the surface of a cylinder.

physt.plotting.matplotlib.fill(h1: Histogram1D, ax: Axes, **kwargs)

Fill plot of 1D histogram.

physt.plotting.matplotlib.globe_map(hist: Histogram2D | SphericalSurfaceHistogram, ax: Axes3D, *, lw: int = 1, show_zero: bool = True, **kwargs)

Heat map plotted on the surface of a sphere.

physt.plotting.matplotlib.image(h2: Histogram2D, ax: Axes, *, density: bool = False, show_colorbar: bool = True, interpolation: str = 'nearest', **kwargs)

Plot of 2D histograms based on pixmaps.

Similar to map, but it: - has fewer options - is much more effective (enables thousands) - does not support irregular bins

Parameters:

interpolation (interpolation parameter passed to imshow, default: "nearest" (creates rectangles))

physt.plotting.matplotlib.line(h1: Histogram1D, ax: Axes, *, show_stats: bool = False, show_values: bool = False, density: bool = False, cumulative: bool = False, errors: bool = False, **kwargs)

Line plot of 1D histogram.

physt.plotting.matplotlib.map(h2: Histogram2D, ax: Axes, *, show_zero: bool = True, show_values: bool = False, show_colorbar: bool = True, value_format: Any = <class 'str'>, x=None, y=None, **kwargs)

Coloured-rectangle plot of 2D histogram.

Parameters:
  • show_zero (Whether to show coloured box for bins with 0 frequency (otherwise background).)

  • show_values (Whether to show labels with frequencies/densities in the middle of the bin)

text_colorOptional

Colour of text descriptions

text_alphaOptional[float]

Alpha for the text labels only

xOptional[Callable]

Transformation of x bin coordinates

yOptional[Callable]

Transformation of y bin coordinates

zorderfloat

z-order in the axis (higher number above lower)

Notes

If you transform axes using x or y parameters, the deduction of axis limits does not work well automatically. Please, make sure to attend to it yourself. The densities in transformed maps are calculated from original bins.

physt.plotting.matplotlib.pair_bars(first: Histogram1D, second: Histogram1D, *, orientation: str = 'vertical', kind: str = 'bar', **kwargs) Axes

Draw two different histograms mirrored in one figure.

Parameters:
  • first

  • second

  • color1 (Color for the first histogram)

  • color2 (Color for the second histogram)

  • orientation (vertical (not enabled yet) or horizontal)

physt.plotting.matplotlib.polar_map(hist: Histogram2D, ax: Axes, *, show_zero: bool = True, show_colorbar: bool = True, **kwargs)

Polar map of polar histograms.

Similar to map, but supports less parameters.

physt.plotting.matplotlib.register(*dim: int, use_3d: bool = False, use_polar: bool = False, collection: bool = False)

Decorator to wrap common plotting functionality.

Parameters:
  • dim (Dimensionality of histogram for which it is applicable)

  • use_3d (If True, the figure will be 3D.)

  • use_polar (If True, the figure will be in polar coordinates.)

  • collection (Whether to allow histogram collections to be used)

physt.plotting.matplotlib.scatter(h1: Histogram1D, ax: Axes, *, errors: bool = False, show_stats: bool = False, show_values: bool = False, density: bool = False, cumulative: bool = False, **kwargs)

Scatter plot of 1D histogram.

physt.plotting.matplotlib.step(h1: Histogram1D, ax: Axes, **kwargs)

Step line-plot of 1D histogram.

physt.plotting.matplotlib.surface_map(hist, ax: Axes3D, *, show_zero: bool = True, x=<function <lambda>>, y=<function <lambda>>, z=<function <lambda>>, **kwargs) None

Coloured-rectangle plot of 2D histogram, placed on an arbitrary surface.

Each bin is mapped to a rectangle in 3D space using the x,y,z functions.

Parameters:
  • hist (Histogram2D)

  • show_zero (Optional[bool]) – Whether to show coloured box for bins with 0 frequency (otherwise background).

  • x (function) – Function with 2 parameters used to map bins to spatial x coordinate

  • y (function) – Function with 2 parameters used to map bins to spatial y coordinate

  • z (function) – Function with 2 parameters used to map bins to spatial z coordinate

Return type:

matplotlib.axes._subplots.Axes3DSubplot

physt.plotting.plotly module

Plot.ly backend for plotting in physt.

Currently, it uses matplotlib translation for 1D histograms: - bar - scatter - line

TODO: More elaborate output planned

physt.plotting.plotly.bar(h: HistogramCollection, *, barmode: str = 'overlay', alpha: float = 1.0, **kwargs) Figure

Bar plot.

Parameters:
  • alpha (Opacity (0.0 - 1.0))

  • barmode ("overlay" | "group" | "stack")

physt.plotting.plotly.enable_collection(f: Callable) Callable

Decorator calling the wrapped function with a HistogramCollection as argument.

physt.plotting.plotly.enable_output(f: Callable) Callable
physt.plotting.plotly.line(h: AbstractHistogram1D, **kwargs) go.Figure
physt.plotting.plotly.map(h2: Histogram2D, **kwargs) Figure

Heatmap.

physt.plotting.plotly.scatter(h: AbstractHistogram1D, **kwargs) go.Figure

physt.plotting.vega module

Vega3 backend for plotting in physt.

The JSON can be produced without any external dependency, the ability to show plots in-line in IPython requires ‘vega3’ library.

Implementation note: Values passed to JSON cannot be of type np.int64 (solution: explicit cast to float)

Common parameters

See the enable_inline_view wrapper.

physt.plotting.vega.bar(h1: Histogram1D, **kwargs) dict

Bar plot of 1D histogram.

Parameters:
  • lw (float) – Width of the line between bars

  • alpha (float) – Opacity of the bars

  • hover_alpha (float) – Opacity of the bars when hover on

physt.plotting.vega.display_vega(vega_data: dict, display: bool = True) 'Vega' | dict

Optionally display vega dictionary.

Parameters:
  • vega_data (Valid vega data as dictionary)

  • display (Whether to try in-line display in IPython)

physt.plotting.vega.enable_inline_view(f: Callable) Callable

Decorator to enable in-line viewing in Python and saving to external file.

It adds several parameters to each decorated plotted function:

Parameters:
  • write_to (str (optional)) – Path to write vega JSON/HTML to.

  • write_format ("auto" | "json" | "html") – Whether to create a JSON data file or a full-fledged HTML page.

  • display ("auto" | True | False) – Whether to try in-line display in IPython

  • indent (int) – Indentation of JSON

physt.plotting.vega.line(h1: Histogram1D, **kwargs) dict

Line plot of 1D histogram values.

Points are horizontally placed in bin centers.

Parameters:

h1 (physt.histogram1d.Histogram1D) – Dimensionality of histogram for which it is applicable

physt.plotting.vega.map(h2: Histogram2D, *, show_zero: bool = True, show_values: bool = False, **kwargs) dict

Heat-map of two-dimensional histogram.

physt.plotting.vega.map_with_slider(h3: HistogramND, *, show_zero: bool = True, show_values: bool = False, **kwargs) dict

Heatmap showing slice in first two dimensions, third dimension represented as a slider.

physt.plotting.vega.scatter(h1: Histogram1D, **kwargs) dict

Scatter plot of 1D histogram values.

Points are horizontally placed in bin centers.

Parameters:

shape (str)

physt.plotting.vega.write_vega(vega_data, *, title: str | None, write_to: str, write_format: str = 'auto', indent: int = 2) None

Write vega dictionary to an external file.

Parameters:
  • vega_data (Valid vega data as dictionary)

  • write_to (Path to write vega JSON/HTML to.)

  • write_format ("auto" | "json" | "html") – Whether to create a JSON data file or a full-fledged HTML page.

  • indent (Indentation of JSON)

Module contents

Plotting for physt histograms.

Available backends

  • matplotlib

  • vega

  • plotly (simple wrapper around matplotlib for 1D histograms)

  • folium (just for the geographical histograms)

  • ascii (for the command-line usage)

Calling the plotting functions

Common parameters

There are several backends (and user-defined may be added) and several plotting functions for each - we try to keep a consistent set of parameters to which all implementations should try to stick (with exceptions).

All histograms

write_tostr (optional)

Path to file where the output will be stored

titlestr (optional)

String to be displayed as plot title (defaults to h.title)

xlabelstr (optional)

String to be displayed as x-axis label (defaults to corr. axis name)

ylabelstr (optional)

String to be displayed as y-axis label (defaults to corr. axis name)

xscalestr (optional)

If “log”, x axis will be scaled logarithmically

yscalestr (optional)

If “log”, y axis will be scaled logarithmically

xlim : tuple | “auto” | “keep”

ylim : tuple | “auto” | “keep”

invert_ybool

If True, the y axis points downwards

ticks{“center”, “edge”}, optional

If set, each bin will have a tick (either central or edge)

alphafloat (optional)

The alpha of the whole plot (default: 1)

cmapstr or list

Name of the palette or list of colors or something that the respective backend can interpret as colourmap.

cmap_normalize : {“log”}, optional

cmap_min :

cmap_max :

show_valuesbool

If True, show values next to (or inside) the bins

value_formatstr or Callable

How bin values (if to be displayed) are rendered.

zorder : int (optional)

text_color : text_alpha : text_* :

Other options that are passed to the formatting of values without the prefix

1D histograms

cumulativebool

If True, show CDF instead of bin heights

densitybool

If True, does not show bin contents but contents divided by width

errorsbool

Whether to show error bars (if available)

show_statsbool

If True, display a small box with statistical info

stats_loc: 1 | 2 | 3 | 4 | “upper right” | “upper left” | “lower left” | “lower right”

Where to display the stats box (similar to legend)

stats_title:

What is displayed in the stats box header

2D heatmaps

show_zerobool

Whether to show bins that have 0 frequency

grid_color :

Colour of line between bins

show_colorbarbool

Whether to display a colorbar next to the plot itself

Line plots

lw (or linewidth)int

Width of the lines

class physt.plotting.PlottingProxy(h: HistogramBase | HistogramCollection)

Bases: object

Proxy enabling to call plotting methods on histogram objects.

It can be used both as a method or as an object containing methods. In any case, it only forwards the call to the universal plot() function.

The __dir__ method should offer all plotting methods supported by the currently selected backend.

Example

plotter = histogram.plot plotter(…) # Plots using defaults plotter.bar(…) # Plots as a specified plot type (“bar”)

Note

Inspiration taken from the way how pandas deals with this.

physt.plotting.get_default_backend() str | None

The backend that will be used by default with the plot function.

physt.plotting.plot(histogram: HistogramBase | HistogramCollection, kind: str | None = None, backend: str | None = None, **kwargs)

Universal plotting function.

All keyword arguments are passed to the plotting methods.

Parameters:

kind (Type of the plot (like "scatter", "line", ...), similar to pandas)

physt.plotting.set_default_backend(name: str) None

Choose a default backend.