API

plot

easy_mpl.plot(*args, share_axes: bool = True, show: bool = True, ax: Axes | None = None, ax_kws: dict | None = None, **kwargs) Axes[source]

One liner plot function. It’s use is not more complex than matplotlib.axes.Axes.plot or matplotlib.pyplot.plot . However it accomplishes all in one line what requires multiple lines in matplotlib. args and kwargs can be anything which goes into matplotlib.pyplot.plot or matplotlib.axes.Axes.plot.

Parameters:
Returns:

matplotlib.axes on which the plot is drawn. If show is False, this axes can be used for further processing

Return type:

matplotlib.axes

Example

>>> from easy_mpl import plot
>>> import numpy as np
>>> plot(np.random.random(100))
use x and y
>>> plot(np.arange(100), np.random.random(100))
use x and y
>>> plot(np.arange(100), np.random.random(100), '.')
string after arrays represent marker style
>>> plot(np.random.random(100), '.')
use cutom marker
>>> plot(np.random.random(100), '--*')
using label keyword
>>> plot(np.random.random(100), '--*', label='label')
log transform y-axis
>>> plot(np.random.random(100), '--*', ax_kws={'logy':True}, label='label')

See a. plot for more examples

pie

easy_mpl.pie(vals: list | ndarray | None = None, fractions: list | ndarray | None = None, labels: list | None = None, autopct='%1.1f%%', ax: Axes | None = None, ax_kws: dict | None = None, show: bool = True, **kwargs) tuple[source]

draws the pie chart

Parameters:
  • vals (array like,) – unique values and their counts will be inferred from this array.

  • fractions (list, array, optional) – if given, vals must not be given

  • labels (list, array, optional) – labels for unique values in vals, if given, must be equal to unique vals in vals. Otherwise “unique_value (counts)” will be used for labeling.

  • autopct (str (default='%1.1f%%')) – string defining method to represent percentage. Set this to None to not use this argument.

  • ax (plt.Axes, optional) – the matplotlib.axes on which to draw, if not given current active axes will be used

  • ax_kws (dict, optional) – keyword arguments for easy_mpl.utils.process_axes()

  • show (bool, optional (default=True)) – whether to show the plot or not

  • **kwargs (optional) – any keyword argument will go to matplotlib.axes.Axes.pie

Returns:

same what is returned by matplotlib.axes.Axes.pie

Return type:

outs

Example

>>> import numpy as np
>>> from easy_mpl import pie
>>> pie(np.random.randint(0, 3, 100))
or by directly providing fractions
>>> pie([0.2, 0.3, 0.1, 0.4])
... # to explode 0.3
>>> explode = (0, 0.1, 0, 0, 0)
>>> pie(fractions=[0.2, 0.3, 0.15, 0.25, 0.1], explode=explode)

See j. pie for more examples

bar_chart

easy_mpl.bar_chart(data, labels=None, orient: str = 'h', sort: bool = False, max_bars: int = None, errors=None, color=None, cmap: str | List[str] = None, rotation: int = 0, bar_labels: list | ndarray = None, bar_label_kws=None, share_axes: bool = True, width=None, ax: Axes = None, ax_kws: dict = None, show: bool = True, **kwargs) Axes | List[Axes][source]

plots bar chart

Parameters:
  • data (array like) – array like e.g. list/numpy array/ pandas series/ pandas dataframe / tuple alias for “values”.

  • labels (list, optional) – used for labeling each bar

  • orient (str, optional) – orientation of bars. either ‘h’ or ‘v’

  • sort (bool, optional (default=None)) – whether to sort the bars based upon their values or not

  • max_bars (int, optional (default=None)) – maximum number of bars to show

  • errors (list, optional) – for error bars

  • color (bool, optional (default=None)) – color for bars. It can any color value valid for matplotlib.

  • cmap (str, optional (default=None)) – matplotlib colormap

  • rotation (int, optional) – rotation angle of ticklabels

  • bar_labels (list) – labels of the bars

  • bar_label_kws (dict) – keyword arguments for matplotlib.axes.Axes.bar_label

  • share_axes (bool (default=True)) – only relevant if given array is 2 dimentional. In such a case, this refers to whether to draw two bar charts on same axes or on two separate axes

  • width (float) – width of the bars

  • ax (matplotlib.axes, optional) – If not given, current available axes will be used

  • ax_kws (dict, optional) – any keyword arguments for processing of axes that will go to easy_mpl.utils.process_axes()

  • show (bool, optional) – whether to show the plot or not

  • **kwargs – any additional keyword arguments for matplotlib.axes.Axes.bar or matplotlib.axes.Axes.barh

Returns:

matplotlib Axes or list of matplotlib Axes on which the bar_chart is drawn. If show is False, this axes can be used for further processing

Return type:

matplotlib.axes

Examples

>>> from easy_mpl import bar_chart
>>> bar_chart([1,2,3,4,4,5,3,2,5])
specifying labels
>>> bar_chart([3,4,2,5,10], ['a', 'b', 'c', 'd', 'e'])
sorting the data
>>> bar_chart([1,2,3,4,4,5,3,2,5], sort=True)
multiple bar charts
>>> bar_chart(np.random.randint(0, 10, (5, 2)), color=['salmon', 'cadetblue'])

See d. bar_chart for more examples

hist

easy_mpl.hist(data: list | ndarray, labels: str | List[str] = None, share_axes: bool = True, grid: bool = True, subplots_kws: dict = None, add_kde: bool = False, kde_kws: dict = None, line_kws: dict = None, ax: Axes = None, ax_kws: dict = None, show: bool = True, return_axes: bool = False, **kwargs)[source]

one stop shop for histogram

Parameters:
  • data (list, array, optional) – array like, numpy ndarray or pandas DataFrame, or list of arrays

  • labels (list/str optional) – names of the arrays, used for setting the legend

  • share_axes (bool (default=True)) – whether to draw all the histograms on one axes or not?

  • grid (bool, optional) – whether to show the grid or not

  • subplots_kws (dict) – kws which go to plt.subplots() such as figure size (width, height)

  • add_kde (bool, (default=False)) – whether to add a line representing kernel densitiy estimation or not

  • kde_kws (dict) – keyword arguments to calculate kde. These will go to easy_mpl.utils.kde() function.

  • line_kws (dict) – keyword arguments for drawing the kde line. These will go to matplotlib.axes.Axes.plot function

  • ax (plt.Axes, optional) – axes on which to draw the plot

  • ax_kws (dict) – keyword arguments for easy_mpl.utils.process_axes()

  • show (bool, optional) – whether to show the plot or not

  • return_axes (bool, (default=False)) – whether to return the axes objects on which histogram/histograms are drawn or not. If True, then the function returns two objects, the first is a tuple (output of axes.hist) and second is the axes/list of axes on which histogram is drawn

  • **kwargs (optional) – any keyword arguments for matplotlib.axes.Axes.hist

Return type:

same what is returned by matplotlib.axes.Axes.hist

Example

>>> from easy_mpl import hist
>>> import numpy as np
>>> hist(np.random.random((10, 1)))

See e. hist for more examples

regplot

easy_mpl.regplot(x: ndarray | list, y: ndarray | list, label: str | None = None, marker_size: int | float = 20, marker_color=None, scatter_kws: dict | None = None, line_style='-', line_color=None, line_kws: dict | None = None, ci: int | None = 95, fill_color=None, figsize: tuple | None = None, marginals: bool = False, marginal_ax_size: float | List[float] = 0.7, marginal_ax_pad: float | List[float] = 0.25, ridge_line_kws: dict | List[dict] | None = None, fill_kws: dict | List[dict] | None = None, hist: bool = True, hist_kws: dict | List[dict] | None = None, ax: Axes | None = None, ax_kws: dict | None = None, show: bool = True) Axes[source]

Regpression plot with regression line and confidence interval

Parameters:
  • x (array like, optional) – the ‘x’ value. It can be numpy array, pandas DataFram/Series or a list

  • y (array like, optional) – It can be numpy array, pandas DataFram/Series or a list

  • ci (int, optional) – confidence interval. Set to None if not required.

  • label (str, optional) – Label to use as legend. The value to annotate with.

  • marker_size (int, optional) – size of marker

  • marker_color (optional) – color of marker

  • scatter_kws (dict) – keyword arguments for matplotlib.axes.scatter

  • line_style (str (default='-')) – line style will be used as ax.plot(x,y,line_style) Set this to None if you don’t want to plot line

  • line_color (optional) – color of line

  • line_kws (dict) – keyword arguments for axes.plot for line plot

  • fill_color (optional) – only relevent if ci is not None.

  • figsize (tuple, optional) – figure size (width, height)

  • marginals (bool (default=False)) – whether to draw the marginal plots or not. If yes, marginal plots will be drawn using easy_mpl.utils.AddMarginalPlots

  • marginal_ax_size – size of marginal axes. If given as list, the first argument is taken for horizontal marginal axes and second argument for vertical merginal axees. It is only valid if marginals is set to True.

  • marginal_ax_pad – pad value for marginal axes. If given as list, the first argument is taken for horizontal marginal axes and second argument for vertical merginal axees. It is only valid if marginals is set to True.

  • ridge_line_kws

    keyword arguments for a:obj:`matplotlib.axes.Axes.plot to draw the

    kde.

    It can be dictionary or list of two dictionaries, where first dictionary is for hoziontal marginal axes and second dictionary is for vertical marginal axes

  • fill_kws (dict/List[dict] (default=None)) – keyword arguments for matplotlib.axes.Axes.fill_between. It can be dictionary or list of two dictionaries, where first dictionary is for hoziontal marginal axes and second dictionary is for vertical marginal axes

  • hist (bool) – whether to draw the histogram or not on marginal axes

  • hist_kws – keyword arguments for matplotlib.axes.Axes.hist. It can be dictionary or list of two dictionaries, where first dictionary is for hoziontal marginal axes and second dictionary is for vertical marginal axes

  • ax (plt.Axes, optional) – matplotlib axes matplotlib.axes to draw plot on. If not given, current avaialable will be used.

  • ax_kws (dict (default=None)) – keyword arguments for easy_mpl.utils.process_axes()

  • show (bool, optional) – whether to show the plot or not

Returns:

the matplotlib Axes matplotlib.axes on which regression plot is drawn.

Return type:

matplotlib.pyplot.Axes

Examples

>>> import numpy as np
>>> from easy_mpl import regplot
>>> x_, y_ = np.random.random(100), np.random.random(100)
>>> regplot(x_, y_)

See h. regplot for more examples

Note

If nans are present in x or y, they will be removed.

imshow

easy_mpl.imshow(values, yticklabels=None, xticklabels=None, annotate: bool = False, annotate_kws: dict | None = None, colorbar: bool = False, grid_params: dict | None = None, mask: bool | str | ndarray | None = None, cbar_params: dict | None = None, ax: Axes | None = None, ax_kws: dict | None = None, show: bool = True, **kwargs)[source]

One stop shop for matplotlib’s imshow function

Parameters:
  • values (2d array) – the image/data to show. It must bt 2 dimensional. It can also be dataframe.

  • annotate (bool, optional) – whether to annotate the heatmap or not

  • annotate_kws (dict, optional) –

    a dictionary with following possible keys

    • ha : horizontal alighnment (default=”center”)

    • va : vertical alighnment (default=”center”)

    • fmt : format (default=’%.2f’)

    • textcolors : colors for axes.text

    • threshold : threshold to be used for annotation

    • **kws : any other keyword argument for axes.text

  • colorbar (bool, optional) – whether to draw colorbar or not

  • xticklabels (list, optional) – tick labels for x-axis. For DataFrames, column names are used by default.

  • yticklabels (list, optional) – tick labels for y-axis. For DataFrames, index is used by default

  • grid_params (dict, optional (default=None)) –

    parameters to process grid. Allowed keys in the dictionary are following
    • border, bool

    • linestyle

    • linewidth

    • color

  • mask

    This argument can be used to hide part of heatmap from being displayed.
    • True : will only show the lower half

    • upper will only show the lower half

    • lower will only show the upper half

  • cbar_params (dict, optional) – parameters that will go to :py:func`easy_mpl.utils.process_cbar` for colorbar. For example pad or orientation

  • ax (plt.Axes, optional) – if not given, current available axes will be used

  • ax_kws (dict, optional (default=None)) – any keyword arguments for easy_mpl.utils.process_axes() function as dictionary

  • show (bool, optional) – whether to show the plot or not

  • **kwargs (optional) – any further keyword arguments for matplotlib.axes.Axes.imshow

Returns:

a matplotlib.image.AxesImage

Return type:

matplotlib.image.AxesImage

Examples

>>> import numpy as np
>>> from easy_mpl import imshow
>>> x = np.random.random((10, 5))
>>> imshow(x, annotate=True)
... # show colorbar
>>> imshow(x, colorbar=True)
... # setting white grid lines and annotation
>>> data = np.random.random((4, 10))
>>> imshow(data, cmap="YlGn",
...        xticklabels=[f"Feature {i}" for i in range(data.shape[1])],
...        grid_params={'border': True, 'color': 'w', 'linewidth': 2}, annotate=True,
...        colorbar=True)

See c. imshow for more examples

scatter

easy_mpl.scatter(x, y, colorbar: bool = False, colorbar_orientation: str = 'vertical', marker_labels: list | ndarray | None = None, text_kws: dict | None = None, xoffset=0.1, yoffset=0.1, ax: Axes | None = None, ax_kws: dict | None = None, show: bool = True, **kwargs) Tuple[Axes, PathCollection][source]

scatter plot between two arrays x and y

Parameters:
  • x (list, array) – data for x-axis

  • y (list, array) – data for y-axis

  • colorbar (bool, optional) – whether to show the color bar or not

  • colorbar_orientation (str, optional) – orientation of colorbar. Only relevant if colorbar is True

  • marker_labels (list, array) – labels to annotate each marker. If given, each value must correspond to respective values in x,y arrays

  • text_kws (dict) – only relevant if marker_labels are provided.

  • xoffset (float) –

  • yoffset (float) –

  • ax (plt.Axes, optional) – matplotlib.axes, if not given, current available axes will be used

  • ax_kws (dict (default=None)) – any keyword arguments for processing of axes which will be forwarded to easy_mpl.utils.prcess_axis()

  • show (bool, optional (default=True)) – whether to show the plot or not

  • **kwargs (optional) – any additional keyword arguments for matplotlib.axes.Axes.scatter

Returns:

A tuple whose first member is matplotlib.axes and second member is matplotlib.collections.PathCollection

Return type:

tuple

Examples

>>> from easy_mpl import scatter
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> x_ = np.random.random(100)
>>> y_ = np.random.random(100)
>>> scatter(x_, y_, show=False)
... # show colorbar
>>> scatter(x_, y_, colorbar=True, show=False)
... # retrieve axes for further processing
>>> axes, _ = scatter(x_, y_, show=False)
>>> assert isinstance(axes, plt.Axes)

See b. scatter for more examples

contour

easy_mpl.contour(x, y, z, fill_between: bool = False, show_points: bool = False, colorbar: bool = True, label_contours: bool = False, fill_between_kws: dict | None = None, show_points_kws: dict | None = None, label_contour_kws: dict | None = None, ax: Axes | None = None, show: bool = True, ax_kws: dict | None = None, **kwargs)[source]

A contour plot of irregularly spaced data coordinates.

Parameters:
  • x (array, list) – a 1d array defining grid positions along x-axis

  • y (array, list) – a 1d array defining grid positions along y-axis

  • z (array, list) – values on grids/points defined by x and y

  • fill_between (bool, optional) – whether to fill the space between colors or not

  • show_points (bool, optional) – whether to show the

  • label_contours (bool, optional) – whether to label the contour lines or not

  • colorbar (bool, optional) – whether to show the colorbar or not. Only valid if fill_between is True

  • fill_between_kws (dict, optional) – any keword argument for axes.tricontourf for example levels or cmap.

  • show_points_kws (dict, optional) – any keword argument for axes.plot

  • label_contour_kws (dict, optional) – any keword argument for axes.clabel

  • ax (plt.Axes, optional) – matplotlib axes to work on. If not given, current active axes will be used.

  • ax_kws (dict optional) – any keyword arguments for easy_mpl.utils.process_axes().

  • show (bool, optional) – whether to show the plot or not

  • **kwargs – any keword argument for axes.tricontour

Returns:

a matplotliblib Axes

Return type:

plt.Axes

Examples

>>> from easy_mpl import contour
>>> import numpy as np
>>> _x = np.random.uniform(-2, 2, 200)
>>> _y = np.random.uniform(-2, 2, 200)
>>> _z = _x * np.exp(-_x**2 - _y**2)
>>> contour(_x, _y, _z, fill_between=True, show_points=True)
... # show contour labels
>>> contour(_x, _y, _z, label_contours=True, show_points=True)

See k. contour for more examples

Note

The length of x and y should be same. The actual grid is created using axes.tricontour and axes.tricontourf functions.

dumbbell

easy_mpl.dumbbell_plot(start, end, labels=None, line_color=None, start_marker_color=None, end_marker_color=None, start_kws: dict | None = None, end_kws: dict | None = None, line_kws: dict | None = None, sort_start: str | None = None, sort_end: str | None = None, ax: Axes | None = None, ax_kws: dict | None = None, show: bool = True) Tuple[Axes, PathCollection, PathCollection][source]

Dumbell plot which indicates variation of several variables from start to end.

Parameters:
  • start (list, array, series) – an array consisting of starting values

  • end (list, array, series) – an array consisting of end values

  • labels (list, array, series, optional) – names of values in start/end arrays. It is used to label ticklabcls on y-axis

  • line_color – color for lines. This can be a color name, rbg value, array of rbg values for each marker or a color palette name. This can be used to have separate color for a each line.

  • start_marker_color – color for starting markers. This can be a color name, rbg value, array of rbg values for each marker or a color palette name. This can be used to have separate color for a each marker.

  • end_marker_color – color for end markers. T This can be a color name, rbg value, array of rbg values for each marker or a color palette name. his can be used to have separate color for a each marker.

  • start_kws (dict, optional) – any additional keyword arguments for easy_mpl.utils.scatter() to modify start markers such as color, label etc

  • end_kws (dict, optional) – any additional keyword arguments for easy_mpl.utils.scatter() to modify end markers such as color, label etc

  • line_kws (dict, optional) – any additional keyword arguments for lines.Line2D to modify line style/color which connects dumbbells.

  • sort_start (str (default=None)) – either “ascend” or “descend”

  • sort_end (str (default=None)) – either “ascend” or “descend”

  • ax (plt.Axes, optional) – matplotlib axes object to work with. If not given then currently available axes will be used.

  • ax_kws (dict optional) – any keyword arguments for easy_mpl.utils.process_axes().

  • show (bool, optional) – whether to show the plot or not

Returns:

Examples

>>> import numpy as np
>>> from easy_mpl import dumbbell_plot
>>> st = np.random.randint(1, 5, 10)
>>> en = np.random.randint(11, 20, 10)
>>> dumbbell_plot(st, en)
... # modify line color
>>> dumbbell_plot(st, en, line_kws={'color':"black"})

See g. dumbbell_plot for more examples

ridge

easy_mpl.ridge(data: ndarray | List[ndarray], bw_method='scott', cut: float = 0.5, color: str | List[str] | ndarray | List[ndarray] | None = None, fill_kws: dict | None = None, line_width: int | List[int] | float | List[float] = 1.0, line_color: str | List[str] = 'black', plot_kws: dict | None = None, xlabel: str | None = None, title: str | None = None, figsize: tuple | None = None, hspace: float = -0.7, labels: str | List[str] | None = None, share_axes: bool = False, ax: Axes | None = None, show=True) List[Axes][source]

plots distribution of features/columns/arrays in data as ridge.

Parameters:
  • data (array, DataFrame) – array or list of arrays or pandas DataFrame/Series

  • bw_method (str, optional) –

  • cut (float (default=0.5)) –

  • color (str, optional) – color to fill the ridges. It can be any valid matplotlib color or color name or cmap name or a list of colors for each ridge.

  • fill_kws (dict, (default=None)) – keyword arguments that will go to matplotlib.axes.Axes.fill_between

  • line_width (int (default=1.0)) – with of line of ridges.

  • line_color (str (default="black")) – color or colors of lines of ridges.

  • plot_kws (dict optional) – any keyword argumenets that will go to matplotlib.axes.Axes.plot during plot of kde line

  • xlabel (str, optional) – xlabel for the figure

  • title (str, optional) – title of the figure

  • figsize (tuple, optional) – size of figure

  • hspace (float, optional (default=-0.7)) – amount of distance between plots

  • labels (list/str (default=None) – names for xticks

  • share_axes (bool, optional (default=False)) – whether to draw all ridges on same axes or separate axes

  • ax (plt.Axes, optional (default=None)) –

    matplotlib axes object matplotlib.axes on which to draw the ridges.

    If given all ridges will be drawn on this axes.

  • show (bool, optional) – whether to show the plot or not

Returns:

a list of matplotlib.axes

Return type:

list

Examples

>>> import numpy as np
>>> from easy_mpl import ridge
>>> data_ = np.random.random((100, 3))
>>> ridge(data_)
... # specifying colormap
>>> ridge(data_, cmap="Blues")
... # using pandas DataFrame
>>> import pandas as pd
>>> ridge(pd.DataFrame(data_))

See i. ridge for more examples

boxplot

easy_mpl.boxplot(data: ndarray | List[ndarray] | List[list], line_color: str | List[str] | None = None, line_width=None, fill_color: str | List[str] | None = None, labels: str | List[str] | None = None, share_axes: bool = True, figsize: tuple | None = None, ax: Axes | None = None, ax_kws: dict | None = None, show: bool = True, **box_kws) Tuple[Axes | List[Axes], List[dict] | dict][source]

Draws the box and whiker plot

Parameters:
  • data – array like (list, numpy array, pandas dataframe/series) or list of array likes. If list of array likes, the length of arrays in the list can be different.

  • line_color – name of color/colors/cmap for lines/boundaries of box, whisker, cap, median and mean line

  • line_width – width of the box lines.

  • fill_color – name of color/colors/cmap to fill the boxes. It can be any valid matplotlib color or cmap.

  • labels (str/list (default=None)) – used for ticklabels of x-axes

  • share_axes (bool (default=True)) – whether to draw all the histograms on one axes or not

  • figsize (tuple (default=None)) – figure size as tuple (width, height)

  • ax (plt.Axes, optional (default=None)) – matploltib axes on which to draw the plot

  • ax_kws (dict (default=None)) – keyword arguments of easy_mpl.utils.process_axes()

  • show (bool (default=show)) – whether to show the plot or not

  • **box_kws – any additional keyword argument for matplotlib.axes.Axes.boxplot

Returns:

a tuple of two
  • plt.Axes or list of matplotlib.axes

  • a dictionary or list of dictionaries which consists of boxes, medians, whiskers, fliers

Return type:

tuple

Examples

>>> from easy_mpl import boxplot
>>> boxplot(np.random.random((100, 5)))
we can also provide arrays of different lengths
>>> boxplot([np.random.random(100), np.random.random(90)])
the color can be given as either color name or colormap
>>> boxplot(np.random.random((100, 3)), fill_color=['pink', 'lightblue', 'lightgreen'])
>>> boxplot(np.random.random((100, 3)), fill_color="viridis")

See p. boxplot for more examples

parallel_coordinates

easy_mpl.parallel_coordinates(data: ndarray | Any, categories: list | ndarray | None = None, names: list | None = None, cmap: str | None = None, linestyle: str = 'bezier', coord_title_kws: dict | None = None, title: str = 'Parallel Coordinates Plot', figsize: tuple | None = None, ticklabel_kws: dict | None = None, show: bool = True) Axes[source]

parallel coordinates plot modifying after https://stackoverflow.com/a/60401570/5982232

Parameters:
  • data (array, DataFrame) – a two dimensional array with the shape (rows, columns). It can also be pandas DataFrame

  • categories (list, array) – 1 dimensional array which contain class labels of the of each row in data. It can be either categorical or continuous numerical values. If not given, colorbar will not be drawn. The length of categroes array must be equal to length of/rows in data.

  • names (list, optional) – Labels for columns in data. It’s length should be equal to number of oclumns in data.

  • cmap (str, optional) – colormap to be used

  • coord_title_kws (dict, optional) – keyword arguments for coodinate titles. All of these arguments will go to matplotlib.axes.Axes.set_xticklabels

  • linestyle (str, optional) – either “straight” or “bezier”. Default is “bezier”.

  • title (str, optional) – title for the Figure

  • figsize (tuple, optional) – figure size

  • ticklabel_kws (dict, optional) – keyword arguments for ticklabels on y-axis

  • show (bool, optional) – whether to show the plot or not

Return type:

matplotlib Axes

Examples

>>> import random
>>> import numpy as np
>>> import pandas as pd
>>> from easy_mpl import parallel_coordinates
...
>>> ynames = ['P1', 'P2', 'P3', 'P4', 'P5']  # feature/column names
>>> N1, N2, N3 = 10, 5, 8
>>> N = N1 + N2 + N3
>>> categories_ = ['a', 'b', 'c', 'd', 'e', 'f']
>>> y1 = np.random.uniform(0, 10, N) + 7
>>> y2 = np.sin(np.random.uniform(0, np.pi, N))
>>> y3 = np.random.binomial(300, 1 / 10, N)
>>> y4 = np.random.binomial(200, 1 / 3, N)
>>> y5 = np.random.uniform(0, 800, N)
... # combine all arrays into a pandas DataFrame
>>> data_np = np.column_stack((y1, y2, y3, y4, y5))
>>> data_df = pd.DataFrame(data_np, columns=ynames)
... # using a DataFrame to draw parallel coordinates
>>> parallel_coordinates(data_df, names=ynames)
... # using continuous values for categories
>>> parallel_coordinates(data_df, names=ynames, categories=np.random.randint(0, 5, N))
... # using categorical classes
>>> parallel_coordinates(data_df, names=ynames, categories=random.choices(categories_, k=N))
... # using numpy array instead of DataFrame
>>> parallel_coordinates(data_df.values, names=ynames)
... # with customized tick labels
>>> parallel_coordinates(data_df.values, ticklabel_kws={"fontsize": 8, "color": "red"})
... # using straight lines instead of bezier
>>> parallel_coordinates(data_df, linestyle="straight")
... # with categorical class labels
>>> data_df['P5'] = random.choices(categories_, k=N)
>>> parallel_coordinates(data_df, names=ynames)
... # with categorical class labels and customized ticklabels
>>> data_df['P5'] = random.choices(categories_, k=N)
>>> parallel_coordinates(data_df,  ticklabel_kws={"fontsize": 8, "color": "red"})

See m. parallel_coordinates for more examples

Note

If nans are present in data or categories, all the corresponding enteries/rows will be removed.

taylor_plot

easy_mpl.taylor_plot(observations: dict | ndarray, simulations: dict | ndarray, axis_locs: dict | None = None, cont_kws: dict | None = None, grid_kws: dict | None = None, leg_kws: dict | None = None, axis_fontdict: dict | None = None, axis_kws: dict | None = None, marker_kws: dict | None = None, **kwargs) Figure[source]

Helper function to plot Taylor’s plot. A taylor plot is useful to compare results of different simulations.

Parameters:
  • observations – dict, array If it is an array then it means we have only one scenario. If it is a dictionary of length > 1, then its keys are scenarios and values represent true/observations at that scenarios. The values can also be a dictionary containing std, which stands for standard deviation.

  • simulations – dict A dictionary of length > 1 whose keys are scenarios and whose values are also dictionary. Each sub-dictionary i.e. dictionary of scenario consist of models/simulations.

  • axis_locs

    dict, optional dictionary defining axis orientation of figure. For example with two scenarios named ‘scenario1’ and ‘scenario2’, if we want to plot two plots in one column, then this argument will be

    >>>          {'scenario1': 211,
    >>>           'scenario2': 212}.
    

    Default is None.

  • cont_kws

    dict, optional keyword arguments related to contours. Following args can be used:

    • levels level of contours

    • colors color of contours

    • label_fs fontsize of labels

    • label_fmt format of labels

    • linewidths float or sequence of floats

    • linestyles {None, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}

  • grid_kws

    dict, optional keyword arguments related to grid. Following args can be used. Following keyword arguments are allowed:

    • title_fontsize: int, fontsize of the axis title

    • which {‘major’, ‘minor’, ‘both’}

    • axis {‘both’, ‘x’, ‘y’},

    any kwargs from axes.grid are allowed.

  • leg_kws

    dict, optional keyword arguments related to legends:

    • position defaults to center

    • fontsize int or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’,

      ’x-large’, ‘xx-large’}

    • numpoints int, default: rcParams[“legend.numpoints”] (default: 1)

    • markerscale float, default: rcParams[“legend.markerscale”] (default: 1.0)

    see axes.legend for more details.

    >>> example leg_kws = {'loc': 'upper right', 'numpoints': 1, 'fontsize': 15,
    ...                    'markerscale': 1}
    

  • axis_fontdict

    dict, optional dictionary defining propertiies of left, bottom and top axis labels

    >>> axis_fontdict = {'left': {'fontsize': 20, 'color': 'k', 'ticklabel_fs': 14},
    ...                 'bottom': {'fontsize': 20, 'color': 'g', 'ticklabel_fs': 14},
    ...                 'top': {'fontsize': 20, 'color': 'k', 'ticklabel_fs': 14}}
    

    The user can define properties of either one or all axis.

  • axis_kws – dict, optional dictionary containing general parameters related to axis such as title.

  • marker_kws – dict, optional dictionary containing marker properties. All of these keywords are passed to matplotlib.axes.Axes.plot.

  • **kwargs

    Following keyword arguments are optional:

    • add_ith_interval : bool

    • plot_biasbool, if True, the size of the markers will be used to

      represent bias. The markers will be triangles with their sides up/down depending upon value of bias.

    • ref_color : str, color of refrence dot

    • sim_markermarker to use for simulations. It can be any valid

      marker for matplotlib axis/plot. If None, then counting is used. If string, then same marker is used for all simulations. If dict, keys of dict should match with names of models in simulations dictionary.

    • true_label : label to use for trues. Default is ‘Reference’.

    • intervalslist, if add_ith_interval is True, then this argument is used. It

      must be list of lists or list of tuples, where the inner tuple/list must consist of two values one each for x and y.

    • colors2d numpy array, defining colors. The first dimension

      should be equal to number of models.

    • extend : bool, default False, if True, will plot negative correlation

    • figsize : tuple defining figsize, default is (11,8).

    • show : bool whether to show the plot or not

Returns:

matplotlib figure

Example

>>> import numpy as np
>>> from easy_mpl import taylor_plot
>>> np.random.seed(313)
>>> observations =  np.random.normal(20, 40, 10)
>>> simulations =  {"LSTM": np.random.normal(20, 40, 10),
...             "CNN": np.random.normal(20, 40, 10),
...             "TCN": np.random.normal(20, 40, 10),
...             "CNN-LSTM": np.random.normal(20, 40, 10)}
>>> taylor_plot(observations=observations,
...             simulations=simulations,
...             title="Taylor Plot")
...
... # multiple taylor plots in one figure
>>> np.random.seed(313)
>>> observations = {
...     'site1': np.random.normal(20, 40, 10),
...     'site2': np.random.normal(20, 40, 10),
...     'site3': np.random.normal(20, 40, 10),
...     'site4': np.random.normal(20, 40, 10),
... }
...
>>> simulations = {
...     "site1": {"LSTM": np.random.normal(20, 40, 10),
...                 "CNN": np.random.normal(20, 40, 10),
...                 "TCN": np.random.normal(20, 40, 10),
...                 "CNN-LSTM": np.random.normal(20, 40, 10)},
...
...     "site2": {"LSTM": np.random.normal(20, 40, 10),
...                 "CNN": np.random.normal(20, 40, 10),
...                 "TCN": np.random.normal(20, 40, 10),
...                 "CNN-LSTM": np.random.normal(20, 40, 10)},
...
...     "site3": {"LSTM": np.random.normal(20, 40, 10),
...                 "CNN": np.random.normal(20, 40, 10),
...                 "TCN": np.random.normal(20, 40, 10),
...                 "CNN-LSTM": np.random.normal(20, 40, 10)},
...
...     "site4": {"LSTM": np.random.normal(20, 40, 10),
...                 "CNN": np.random.normal(20, 40, 10),
...                 "TCN": np.random.normal(20, 40, 10),
...                 "CNN-LSTM": np.random.normal(20, 40, 10)},
... }
... # define positions of subplots
>>> rects = dict(site1=221, site2=222, site3=223, site4=224)
...
>>> taylor_plot(observations=observations,
...             simulations=simulations,
...             axis_locs=rects,
...             plot_bias=True,
...             cont_kws={'colors': 'blue', 'linewidths': 1.0, 'linestyles': 'dotted'},
...             grid_kws={'axis': 'x', 'color': 'g', 'lw': 1.0},
...             title="mutiple subplots")
...

Sometimes we don’t have actual observation and simulation values as arrays. We can still make Taylor plot by providing only standard deviation of observations and simulations and coefficient of correlation (R) values between simulations and observations.

>>> observations = {'std': 4.916}
>>> predictions = {   # pbias is optional
...         'Model 1': {'std': 2.80068, 'corr_coeff': 0.49172, 'pbias': -8.85},
...         'Model 2': {'std': 3.47, 'corr_coeff': 0.67, 'pbias': -19.76},
...         'Model 3': {'std': 3.53, 'corr_coeff': 0.596, 'pbias': 7.81},
...         'Model 4': {'std': 2.36, 'corr_coeff': 0.27, 'pbias': -22.78},
...         'Model 5': {'std': 2.97, 'corr_coeff': 0.452, 'pbias': -7.99}}
...
>>> taylor_plot(observations,
...     predictions,
...     title="with statistical parameters")
...
... # with customized markers
>>> np.random.seed(313)
>>> observations =  np.random.normal(20, 40, 10)
>>> simulations =  {"LSTM": np.random.normal(20, 40, 10),
...                 "CNN": np.random.normal(20, 40, 10),
...                 "TCN": np.random.normal(20, 40, 10),
...                 "CNN-LSTM": np.random.normal(20, 40, 10)}
>>> taylor_plot(observations=observations,
...             simulations=simulations,
...             title="customized markers",
...             marker_kws={'markersize': 10, 'markeredgewidth': 1.5,
...                 'markeredgecolor': 'black'})
...
... # with customizing bbox
>>> np.random.seed(313)
>>> observations =  np.random.normal(20, 40, 10)
>>> simus =  {"LSTMBasedRegressionModel": np.random.normal(20, 40, 10),
...         "CNNBasedRegressionModel": np.random.normal(20, 40, 10),
...         "TCNBasedRegressionModel": np.random.normal(20, 40, 10),
...         "CNN-LSTMBasedRegressionModel": np.random.normal(20, 40, 10)}
>>> taylor_plot(observations=observations,
...             simulations=simus,
...             title="custom_legend",
...             leg_kws={'facecolor': 'white',
...                 'edgecolor': 'black','bbox_to_anchor':(1.1, 1.05)})

See o. taylor plot for more examples

lollipop_plot

easy_mpl.lollipop_plot(y, x=None, orientation: str = 'vertical', sort: bool = False, line_style: str = '-', line_color: str = 'cyan', line_width: int = 1, line_kws: dict | None = None, marker_style: str = 'o', marker_color: str = 'teal', marker_size: int = 30, marker_kws: dict | None = None, ax: Axes | None = None, ax_kws: dict | None = None, show: bool = True, **kwargs) Axes[source]

Plot a lollipop plot.

Parameters:
  • y (array_like, shape (n,), optional) – The y-coordinates of the data points.

  • x (array_like, shape (n,)) – The x-coordinates of the data points.

  • orientation (str, optional) – The orientation of the lollipops. Either “vertical” or “horizontal”.

  • sort (bool, optional) – Whether to sort the data points by their values or not. Only valid if x is not specified.

  • line_style (str, optional) – The line style of the data points.

  • line_color (str, optional) – The line color of the data points.

  • line_width (float, optional) – The line width of the data points.

  • line_kws (dict, optional) – The keyword arguments for the line. These arguments are passed to matplotlib.axes.Axes.plot.

  • marker_style (str, optional) – The marker style of the data points.

  • marker_color (str, optional) – The marker color of the data points.

  • marker_size (float, optional) – The marker size of the data points.

  • marker_kws (dict, optional) – The keyword arguments for the marker. These arguments are passed to matplotlib.axes.Axes.scatter.

  • ax (matplotlib.axes.Axes, optional) – The axes to plot on. If not given, current available axes will be used.

  • ax_kws (dict, optional) – any keyword arguments for easy_mpl.utils.process_axes().

  • show (bool, optional (default=True)) – whether to show the plot or not

  • **kwargs (optional) – Additional keyword arguments to pass to the process_axis function.

Returns:

The axes on which the plot was drawn.

Return type:

plt.Axes

Examples

>>> import numpy as np
>>> from easy_mpl import lollipop_plot
>>> y = np.random.randint(0, 10, size=10)
... # vanilla lollipop plot
>>> lollipop_plot(y, title="vanilla")
... # use both x and y
>>> lollipop_plot(y, np.linspace(0, 100, len(y)), title="with x and y")
... # use custom line style
>>> lollipop_plot(y, line_style='--', title="with custom linestyle")
... # use custom marker style
>>> lollipop_plot(y, marker_style='D', title="with custom marker style")
... # sort the data points before plotting
>>> lollipop_plot(y, sort=True, title="sort")
... # horzontal orientation of lollipops
>>> y = np.random.randint(0, 20, size=10)
>>> lollipop_plot(y, orientation="horizontal", title="horizontal")

See f. lollipop_plot for more examples

circular_bar_plot

easy_mpl.circular_bar_plot(data, labels: list | None = None, sort: bool = False, color: str | list | ndarray | None = None, label_format: str | None = None, min_max_range: tuple | None = None, label_padding: int = 4, figsize: tuple | None = None, text_kws: dict | None = None, colorbar: bool = False, ax: Axes | None = None, ax_kws: dict | None = None, show: bool = True, **kwargs) Axes[source]

Plot a circular bar plot.

Parameters:
  • data (list, np.ndarray, pd.Series, dict) – Data to plot. If it is a dictionary, then its keys will be used as labels and values will be used as data.

  • labels (list, optional) – Labels for each data point.

  • sort (bool, optional) – Sort the data by the values.

  • color (str, list, np.ndarray, optional) – Color for each data point. It can be a single color or a colormap from plt.colormaps.

  • label_format (str, optional) – Format for the labels.

  • min_max_range (tuple, optional) – Minimum and maximum range for normalizing the data.

  • label_padding (int, optional) – space between the labels and the bars.

  • figsize (tuple, optional) – Size of the figure.

  • text_kws (dict, optional (default=None)) – keyword arguments for axes.text()

  • colorbar (bool (default=False)) – whether to show the colorbar or not

  • ax (plt.Axes (default=None)) – matplotlib axews with polar projections

  • ax_kws (optional) – Additional keyword arguments to pass to the easy_mpl.utils.process_axes().

  • show (bool, optional (default=True)) – Show the plot.

  • **kwargs – go to matplotlib.axes.Axes.bar

Returns:

Note

If nan values are present in the data, they will be ignored.

Examples

>>> import numpy as np
>>> from easy_mpl import circular_bar_plot
>>> data = np.random.random(50, )
... # basic
>>> circular_bar_plot(data)
... # with names
>>> names = [f"{i}" for i in range(50)]
>>> circular_bar_plot(data, names)
... # sort values
>>> circular_bar_plot(data, names, sort=True)
... # custom color map
>>> circular_bar_plot(data, names, color='viridis')
... # custom min and max range
>>> circular_bar_plot(data, names, min_max_range=(1, 10), label_padding=1)
... # custom label format
>>> circular_bar_plot(data, names, label_format='{} {:.4f}')

spider_plot

easy_mpl.spider_plot(data: ndarray | list, tick_labels: list | None = None, highlight: int | float | None = None, plot_kws: dict | List[dict] | None = None, xtick_kws: dict | None = None, fill_kws: dict | None = None, frame: str = 'circle', color: str | List[str] | None = None, fill_color: str | List[str] | None = None, leg_kws: dict | None = None, labels: list | None = None, show: bool | None = True, figsize: tuple | None = None, ax: Axes | None = None) Axes[source]

Draws spider plot on an axes

Parameters:
  • data (list/numpy array / dict / DataFrame/ Series) – values to display. It should be array like/numpy array or pandas DataFrame/Series

  • tick_labels (list, optional (default=None)) – tick labels. It’s length should be equal to length of values

  • plot_kws (dict, optional (default=None)) – These can include, color, linewidth, linestyle etc

  • xtick_kws (dict, optional (default=None)) – These can include color, size etc.

  • fill_kws (dict, optional) – These can include color, alpha etc.

  • highlight (int/float optional (default=None)) – whether to highlight a certain circular line or not

  • color (str, optional (default=None)) – colormap to use. This color will be used to plot line/lines.

  • frame (str, optional (default="circle")) – whether the outer frame and grids should be polygon or circle

  • figsize (tuple, optional (default=None)) – figure size (width, height)

  • fill_color – color to use for filling

  • leg_kws (dict) – keyword arguments that will go to ax.legend()

  • labels (list, optional (default=None)) – the labels for values

  • show (bool, optional (default=True)) – whether to show the plot or not

  • ax (matplotlib.axes, optional) – axes to use while plotting

Returns:

matplotlib.axes on which plot is drawn

Return type:

plt.Axes

Examples

>>> from easy_mpl import spider_plot
>>> vals = [-0.2, 0.1, 0.0, 0.1, 0.2, 0.3]
>>> spider_plot(values=vals)
... # specifying labels
>>> labels = ['a', 'b','c', 'd', 'e', 'f']
>>> spider_plot(values=vals, labels=labels)
... # specifying tick size
>>> spider_plot(vals, labels, xtick_kws={'size': 13})
... # we can also pass dataframe
>>> import pandas as pd
>>> df = pd.DataFrame.from_dict(
... {'summer': {'a': -0.2, 'b': 0.1, 'c': 0.0, 'd': 0.1, 'e': 0.2, 'f': 0.3},
... 'winter': {'a': -0.3, 'b': 0.1, 'c': 0.0, 'd': 0.2, 'e': 0.15,'f': 0.25}})
>>> spider_plot(df, xtick_kws={'size': 13})
... # use polygon frame
>>> spider_plot(values=vals, frame="polygon")

See n. spider plot for more examples

violin_plot

easy_mpl.violin_plot(data: ndarray | List[ndarray], X: ndarray | List[ndarray] | None = None, fill: bool = True, fill_colors=None, violin_kws: dict | None = None, show_datapoints: bool = True, datapoints_colors: list | str | None = None, scatter_kws: dict | None = None, show_boxplot: bool = False, box_kws: dict | None = None, label_violin: bool = False, index_method: str = 'jitter', max_dots: int | List[int] = 100, cut: float | tuple | List[float] | List[tuple] = 0.2, labels: str | List[str] | None = None, ax: Axes | None = None, show: bool = True) Axes[source]

makes violin plot/plots of the arrays in data

Parameters:
  • data – It can array like or list of arrays. The length of each array need not be equal. If multiple arrays are given, then violin is drawn for each array

  • X – indices for x-axes for each of the array in data. It can be array or list of arrays. If list of arrays is given, the length of arrays can be unequal.

  • fill (bool, optional (default=True)) – whether to fill the violin with color or not

  • fill_colors – colors to fill the violins

  • violin_kws (dict (default=None)) – any keyword arugment for axes.violin in the form of dictionary

  • show_datapoints (bool (default=True)) – whether to plot the datapoints or not

  • datapoints_colors – color for the datapoints/markers

  • scatter_kws (dict (default=None)) – keyword arguments for axes.scatter. This will only be valid if show_datapoints is True.

  • show_boxplot (bool (default=False)) – whether to show the boxplot inside the voilin or not?

  • box_kws (dict (default=None)) – keyword arguments for matplotlib.axes.Axes.boxplot. This will only be valid if show_boxplot is True.

  • label_violin (bool (default=False)) – whether to label mean value of each violin or not

  • index_method (str (default="jitter")) – Only valid if X is not given. The method to generate indices for x-axis. See this <https://stackoverflow.com/a/33965400/5982232>_ for context

  • max_dots (int/list (default=100)) – maximum number of dots to show. It can also be a list of integers, which would define the number of dots for each array in X.

  • cut (float/list (default=0.2)) – This variables determines the length of violin. If given as a list or list of tuples, it should match the number of arrays in X.

  • labels (list/str (default=None) – names for xticks

  • ax (plt.Axes (default=None)) – matplotlib Axes object matplotlib.axes on which to draw the plot. If not given, then the currently available axes from plt.gca will be used.

  • show (bool (default=True)) – whether to show the plot or not

Returns:

the matplotlib Axes object on which violin/violins are drawn

Return type:

plt.Axes

Examples

>>> import numpy as np
>>> from easy_mpl import violin_plot
>>> data = np.random.gamma(20, 10, 100)
>>> violin_plot(data)
>>> violin_plot(data, show_datapoints=False)
>>> violin_plot(data, show_datapoints=False, show_boxplot=True)

See q. violin for more examples

utils

class easy_mpl.utils.AddMarginalPlots(ax: Axes, pad: float = 0.25, size: float = 0.7, hist: bool = True, hist_kws: dict | List[dict] | None = None, ridge: bool = True, ridge_line_kws: dict | List[dict] | None = None, fill_kws: dict | List[dict] | None = None, fix_limits: bool = True)[source]

Adds marginal plots for an axes.

Parameters:
  • ax (plt.Axes) – matplotlib.axes on which to add the marginal plots

  • pad (float) – float or tuple of two. Distance between main axes and marginal axes

  • size – width and height of marginal axes

  • hist (bool (default=True)) – whether to draw histogram on marginal axes or not

  • hist_kws (dict) – keyword arguments that will go to axes.hist function for drawing histograms on maginal plots. It can be a single dictionary or a list of two dictionaries. By default following values are used “linewidth”:0.5, “edgecolor”:”k”

  • ridge (bool (default=True)) – whether to draw ridge line or not

  • ridge_line_kws (dict) – keyword arguments that will go to axes.plot function for drawing ridge line on maginal plots. It can be a single dictionary or a list of two dictionaries

  • fill_kws (dict) – keyword arguments that will go to axes.fill_between function fill between ridge line on maginal plots. Only valid if hist is False. It can be a single dictionary or a list of two dictionaries

  • fix_limits (bool) – If true, then will not shrink/expand the axes after drawing hist/ridge line

Examples

>>> from easy_mpl import plot
>>> x = np.random.normal(size=100)
>>> y = np.random.normal(size=100)
>>> e = x-y
>>> ax = plot(e, show=False)
>>> AddMarginalPlots(ax, hist=True)(x, y)
>>> plt.show()

See r. Adding Marginal plots for more examples

add_ax_marg_x(x_data, hist_kws: dict | None = None, ax: Axes | None = None)[source]

Adds the axes on top of main axes

add_ax_marg_y(y_data, hist_kws: dict | None = None, ax: Axes | None = None)[source]

Adds the axes on right side of main axes

class easy_mpl.utils.NN[source]

A class which can be used to plot fully connected neural networks

Example

>>> from easy_mpl.utils import NN
>>> import matplotlib.pyplot as plt
>>> nn = NN()
>>> nn.add_layer(3, labels=[f'$x_{j}$' for j in range(4)], color='purple')
>>> nn.add_layer(4, color="yellow", linestyle='-')
>>> nn.add_layer(4, color='r')
>>> nn.add_layer(2, labels=['$\mu$', '$\sigma$'], color='g')
>>> _ = nn.plot(spacing=(1, 0.5))
>>> plt.show()

Autoencoder

>>> from easy_mpl.utils import NN
>>> import matplotlib.pyplot as plt
>>> nn = NN()
>>> nn.add_layer(4, labels=[f'$x_{j}$' for j in range(4)], color='#c6dae2',
...         linecolor='#a5a5a5', circle_kws=dict(lw=None))
>>> nn.add_layer(3, color="#e3baac", linestyle=None)
>>> nn.add_layer(3, color='#e3baac', linecolor='#a5a5a5')
>>> nn.add_layer(4, color='#cad09c', circle_kws=dict(lw=None),
...         labels=[f'$y_{j}$' for j in range(4)],)
>>> _ = nn.plot(spacing=(1, 0.5), x_offset=0.18)
>>> plt.show()
add_layer(nodes: int, radius_factor: float = 0.25, labels: List[str] | None = None, color: Any | List[Any] | None = None, linestyle: str | List[str] | None = '-', linecolor: Any | List[Any] = 'k', circle_kws: dict | List[dict] | None = None, line_kws: dict | List[dict] | None = None)[source]
Parameters:
  • nodes (int) – number of nodes to add

  • radius_factor (float (default=0.25)) – determins radius of circles in the layer

  • labels – labels to put inside the circle for each node. If given, then the circle for each node will be labeled accordingly

  • color – color for each circle/circles. If a single color is specified, it will be used for all the cirlces in this layer

  • linestyle – line style for the connections. Set this to None if you don’t want to show connections.

  • linecolor – any keyword arguments for matploltib.axes.Axes.plot

  • circle_kws – keyword arguments for matplotlib.patches.Circle

  • line_kws – any keyword arguments for drawing lines that will go to matplotlib.axes.Axes.plot

Return type:

None

plot(spacing: Tuple[int | float, int | float] = (2, 1), margin: Tuple[float, float] = (0.5, 0.5), x_offset: float = 0.15, ax: Axes | None = None, name: str | None = None, **fig_kws) Axes[source]
Parameters:
  • spacing (tuple) – a tuple which for dx and dy

  • margin

  • x_offset (float) –

  • ax (plt.Axes) – the matplotlib.axes on which to draw, if not given a new axes will be created

  • name (str) – name of file to save the figure

Returns:

matplotlib axes on which the plot is drawn

Return type:

plt.Axes

easy_mpl.utils.add_cbar(ax, mappable, border: bool = True, width: int | float | None = None, pad: int | float = 0.2, orientation: str = 'vertical', title: str | None = None, title_kws: dict | None = None)[source]

makes and processes colobar to an axisting axes

Parameters:
  • ax (plt.Axes) –

  • mappable

  • border (bool) – wether to draw the border or not

  • pad

  • orientation (str) –

  • title (str) –

  • title_kws (dict) – rotation labelpad fontsize weight

Return type:

plt.colorbar

easy_mpl.utils.create_subplots(naxes: int, ax: Axes | None = None, figsize: tuple | None = None, ncols: int | None = None, **fig_kws) Tuple[source]

creates the subplots.

Parameters:
  • naxes (int) – If naxes is 1 and ax is None, then current available axes is returned using plt.gca(). If naxes is 1 and ax is not None, then ax is returned as it is. If naxes > 1 and ax is None, then new axes are created. If naxes > 1 and ax is not None, then ax is closed with a warning and new axes’ are created. If naxes are > 1, then nrows and ncols are calculated automatically unless cols is given. The last redundent axes are switched off in case naxes < (nrows*ncols).

  • ax (plt.Axes) –

  • figsize (tuple) –

  • ncols (int) –

  • **fig_kws – keyword arguments for plt.subplots()

easy_mpl.utils.kde(y: ndarray, bw_method: str = 'scott', bins: int = 1000, cut: float | Tuple[float] = 0.5) Tuple[ndarray | Tuple[ndarray, float | None], Any][source]

Generate Kernel Density Estimate plot using Gaussian kernels.

Parameters:
  • y – array like

  • bw_method – method to calculate

  • bins – number of bins

  • cut

easy_mpl.utils.plot_nn(layers: int, nodes: int | List[int], labels=None, fill_color=None, circle_edge_lw: float | List[float] = 1.0, connection_style: str | List[str] = '-', connection_color='k', spacing: Tuple[int | float, int | float] = (2, 1), margin: Tuple[float, float] = (0.5, 0.5), x_offset: float = 0.15, ax: Axes | None = None, show: bool = True) Axes[source]

function to plot artificial neural networks or multi-layer perceptron

Parameters:
  • layers (int) – number of layers of neural network including input layer and output layer

  • nodes – nodes in layers of neural network. If integer, then same nodes will be used for each layer. Otherwise specify nodes for each layer as list. Each node will be represented as circle.

  • labels – text/label to put inside the circles. If a single string is given, it will be used for all nodes in all layers.

  • fill_color – color to fill the circles/nodes. The user can specify separate color for each node in each layer or a separate color for each layer.

  • circle_edge_lw – width of edge line of circles

  • connection_style – line style for connections

  • connection_color – color to used for line depicting connection of nodes

  • spacing

  • margin

  • x_offset

  • ax (plt.Axes) – the matplotlib.axes on which to draw, if not given a new axes will be created

  • show – whether to show the plot or not

Return type:

plt.Axes

Examples

>>> from easy_mpl.utils import plot_nn
>>> plot_nn(4, [3,4,4,2])
>>> plot_nn(
...     4, nodes=[3, 4, 4, 2],
...     fill_color=['#fff2cc', "#fde6d9", '#dae3f2', '#a9d18f'],
...     labels=[[f'$x_{j}$' for j in range(1,4)], None, None, ['$\mu$', '$\sigma$']],
...     connection_color='#c3c2c3',
...     spacing=(1, 0.5)
...     )

Autoencoder

>>> plot_nn(
...     4,
...     nodes=[4, 3, 3, 4],
...     fill_color=['#c6dae2', "#e3baac", '#e3baac', '#cad09c'],
...     labels=[[f'$x_{j}$' for j in range(4)], None, None, [f'$y_{j}$' for j in range(4)]],
...     connection_color='#a5a5a5',
...     connection_style=['-', None, '-', '-'],
...     circle_edge_lw = [0.0, 1.0, 1.0, 0.],
...     spacing=(1, 0.5),
...     x_offset=0.18
...     )
easy_mpl.utils.process_axes(ax: Axes | None = None, label: str | None = None, legend_kws: dict | None = None, logy: bool = False, logx: bool = False, xlabel: str | None = None, xlabel_kws: dict | None = None, xtick_kws: dict | None = None, ylim: tuple | None = None, ylabel: str | None = None, ylabel_kws: dict | None = None, ytick_kws: dict | None = None, show_xaxis: bool = True, show_yaxis: bool = True, top_spine=None, bottom_spine=None, right_spine=None, left_spine=None, invert_yaxis: bool = False, max_xticks=None, min_xticks=None, title: str | None = None, title_kws: dict | None = None, grid=None, grid_kws: dict | None = None, tight_layout: bool = False) Axes[source]

processing of matplotlib Axes

Parameters:
  • ax (plt.Axes) – the matplotlib.axes axes which needs to be processed.

  • label (str (default=None)) – will be used for legend

  • legend_kws (dict, optional) – dictionary of keyword arguments to matplotlib.axes.Axes.legend These include loc, fontsize, bbox_to_anchor, markerscale

  • logy (bool) – whether to convert y-axes to logrithmic scale or not

  • logx (bool) – whether to convert x-axes to logrithmic scale or not

  • xlabel (str) – label for x-axes

  • xlabel_kws (dict) – keyword arguments for matplotlib.axes.Axes.set_xlabel as ax.set_xlabel(xlabel, **xlabel_kws)

  • xtick_kws – # for axes.tick_params such as which, labelsize, colors etc

  • min_xticks (int) – maximum number of ticks on x-axes

  • max_xticks (int) – minimum number of ticks on x-axes

  • ylabel (str) – label for y-axes

  • ylabel_kws (dict) – ylabel kwargs for matplotlib.axes.Axes.set_ylabel

  • ytick_kws – for axes.tick_params() such as which, labelsize, colors etc

  • ylim – limit for y axes

  • invert_yaxis – whether to invert y-axes or not. It true following command will be executed ax.set_ylim(ax.get_ylim()[::-1])

  • title (str) – title for axes matplotlib.axes.Axes.set_title

  • title_kws (dict) – title kwargs

  • grid – will be fed to ax.grid(grid,…)

  • grid_kws (dict) – dictionary of keyword arguments for ax.grid(grid, **grid_kws)

  • left_spine

  • right_spine

  • top_spine

  • bottom_spine

  • show_xaxis (bool, optional (default=True)) – whether to show x-axes or not

  • show_yaxis (bool, optional (default=True)) – whether to show y-axes or not

  • tight_layout (bool (default=False)) – whether to execulte plt.tight_layout() or not

Returns:

the matplotlib Axes object matplotlib.axes which was passed to this function

Return type:

plt.Axes