rekha.BasePlot¶

class rekha.BasePlot[source]¶

Initialize base plot with common parameters.

This constructor sets up all the common functionality that every Rekha plot needs, including theme configuration, data handling, and styling options.

Parameters:
  • data (pd.DataFrame, dict, or None) –

    The data to plot. Can be:

    • pandas DataFrame with named columns

    • Dictionary with array-like values

    • None if x/y are provided directly as arrays

  • x (str, list, array, or None) –

    X-axis data specification:

    • str: Column name in data

    • array-like: Direct data values

    • None: Use index or default values

  • y (str, list, array, or None) – Y-axis data specification (same format as x)

  • color (str, optional) – Column name in data for color grouping. Creates different colors for each unique value in this column.

  • size (str, list, array, or None) – Column name or data for point/marker sizing (scatter plots)

  • shape (str, optional) – Column name in data for marker shape grouping (scatter plots)

  • facet_row (str, optional) – Column name in data for creating subplot rows. Each unique value in this column creates a separate row of subplots.

  • facet_col (str, optional) – Column name in data for creating subplot columns. Each unique value in this column creates a separate column of subplots.

  • base_plot (BasePlot, optional) – Existing Rekha plot to add to. If provided, this plot will be added to the existing plot’s axes instead of creating a new figure. This enables composition of multiple plot types while staying within the Rekha API.

  • title (str, optional) – Plot title text

  • labels (dict, optional) – Custom axis labels. Maps column names to display labels. Example: {'x_col': 'X Axis Label', 'y_col': 'Y Axis Label'}

  • dark_mode (bool, default False) –

    Whether to use dark theme. When True:

    • Uses dark background colors

    • Switches to light text and grid colors

    • Adjusts color palette for dark backgrounds

  • figsize (tuple, default (10, 6)) – Figure size as (width, height) in inches

  • title_font_size (float, default 16) – Font size for the plot title

  • label_font_size (float, default 14) – Font size for axis labels

  • tick_font_size (float, default 12) – Font size for axis tick labels

  • legend_font_size (float, default 12) – Font size for legend text

  • legend_loc (str, default 'best') – Legend location (‘best’, ‘upper right’, ‘upper left’, ‘lower left’, ‘lower right’, ‘right’, ‘center left’, ‘center right’, ‘lower center’, ‘upper center’, ‘center’)

  • grid (bool, default True) – Whether to show grid lines

  • grid_alpha (float, default 0.6) – Transparency of grid lines (0=invisible, 1=opaque)

  • grid_linewidth (float, default 0.5) – Width of grid lines in points

  • grayscale_friendly (bool, default False) –

    Whether to optimize for grayscale printing:

    • Uses patterns/hatching for differentiation

    • Increases contrast and line weights

    • Uses distinctive markers and line styles

  • color_mapping (dict, optional) – Custom mapping of category values to colors. Example: {'Category A': 'red', 'Category B': 'blue'}

  • category_order (list, optional) – Custom ordering for categorical data. Affects legend order and color assignment.

  • share_x (bool, default True) – Whether to share x-axis across facets. When True, all subplots will have the same x-axis range for easier comparison.

  • share_y (bool, default True) – Whether to share y-axis across facets. When True, all subplots will have the same y-axis range for easier comparison.

  • subplot_titles (bool, default True) – Whether to automatically generate titles for each subplot based on the faceting variables and their values.

  • col_wrap (int, optional) – Maximum number of columns before wrapping to a new row. Useful when faceting by a variable with many categories.

  • row_wrap (int, optional) – Maximum number of rows before wrapping to a new column. Useful when faceting by a variable with many categories.

  • subplot_spacing (float, default 0.3) – Spacing between subplots as a fraction of subplot size. Higher values create more space between plots.

  • margin_spacing (float, default 0.1) – Margin spacing around the entire figure as a fraction of figure size. Controls space for overall title and axis labels.

  • palette (str, default 'rekha') – Color palette to use. Options include ‘rekha’ (default), ‘pastel’, ‘bright’, ‘muted’, ‘colorblind’, etc.

  • xscale (str, optional) – X-axis scale type. Options: ‘linear’, ‘log’, ‘symlog’, ‘logit’. If None, uses matplotlib’s default (usually ‘linear’).

  • yscale (str, optional) – Y-axis scale type. Options: ‘linear’, ‘log’, ‘symlog’, ‘logit’. If None, uses matplotlib’s default (usually ‘linear’).

  • humanize_units (bool, default False) – Whether to format axis tick labels in human-readable form. For example, 1000000 becomes ‘1M’, 1500 becomes ‘1.5K’.

  • humanize_format (str, default 'intword') –

    Format style for humanized numbers:

    • ’intword’: Convert to words (1M, 2.5K)

    • ’intcomma’: Add commas (1,000,000)

    • ’scientific’: Scientific notation (1.0e6)

    • ’fractional’: Convert to fractions where applicable

  • rotate_xticks (bool or float, default False) –

    Whether to rotate x-axis tick labels:

    • False: No rotation (default)

    • True: Rotate 45 degrees

    • float: Rotate by specified degrees (e.g., 30, 45, 90)

  • alpha (float, optional) – Transparency level for plot elements (0=transparent, 1=opaque). Applies to bars, areas, markers, etc. depending on plot type.

  • label (str, optional) – Label for this data series in the legend. If provided, a legend will be automatically shown.

  • edgecolor (str, optional) – Color for edges of plot elements (bars, markers, etc.). Can be a color name, hex code, or RGB tuple.

  • linewidth (float, optional) – Width of lines or edges in points. Applies to different elements depending on plot type (e.g., bar edges, line plots, marker edges).

  • zorder (float, optional) – Drawing order for plot elements. Higher values are drawn on top. Useful for layering multiple plots.

  • **kwargs – Additional keyword arguments passed to the specific plot type. These are plot-specific and passed through to matplotlib functions.

Notes

This class handles the common initialization for all Rekha plots. Specific plot types add their own parameters and override methods as needed while maintaining this consistent base interface.

The color system automatically handles:

  • Categorical color mapping with consistent palettes

  • Dark/light theme switching

  • Grayscale printing optimization

  • Custom color overrides via color_mapping

Methods

add_annotation(text, x, y, **kwargs)

Add annotation to the plot.

get_axes()

Get all axes from the figure.

save(filename[, format, transparent])

Save the plot to file with optimized settings for different use cases.

save_all_formats(base_name, **kwargs)

Save plot in all common formats for different use cases.

show()

Display the plot in the current output (Jupyter notebook, script, etc.).

show_legend()

Manually show the legend with appropriate styling.

update_layout(**kwargs)

Update plot layout - matplotlib style.

__init__(data: DataFrame | Dict | None = None, x: str | List | ndarray | None = None, y: str | List | ndarray | None = None, color: str | None = None, size: str | List | ndarray | None = None, shape: str | None = None, facet_row: str | None = None, facet_col: str | None = None, base_plot: BasePlot | None = None, title: str | None = None, labels: Dict[str, str] | None = None, dark_mode: bool = False, figsize: Tuple[float, float] = (10, 6), title_font_size: float = 16, label_font_size: float = 14, tick_font_size: float = 12, legend_font_size: float = 12, legend_loc: str = 'best', grid: bool = True, grid_alpha: float = 0.6, grid_linewidth: float = 0.5, grayscale_friendly: bool = False, color_mapping: Dict[str, str] | None = None, category_order: List[str] | None = None, share_x: bool = True, share_y: bool = True, subplot_titles: bool = True, col_wrap: int | None = None, row_wrap: int | None = None, subplot_spacing: float = 0.3, margin_spacing: float = 0.1, palette: str = 'rekha', xscale: str | None = None, yscale: str | None = None, humanize_units: bool = False, humanize_format: str = 'intword', rotate_xticks: bool | float = False, alpha: float | None = None, label: str | None = None, edgecolor: str | None = None, linewidth: float | None = None, zorder: float | None = None, **kwargs)[source]¶

Initialize base plot with common parameters.

This constructor sets up all the common functionality that every Rekha plot needs, including theme configuration, data handling, and styling options.

Parameters:
  • data (pd.DataFrame, dict, or None) –

    The data to plot. Can be:

    • pandas DataFrame with named columns

    • Dictionary with array-like values

    • None if x/y are provided directly as arrays

  • x (str, list, array, or None) –

    X-axis data specification:

    • str: Column name in data

    • array-like: Direct data values

    • None: Use index or default values

  • y (str, list, array, or None) – Y-axis data specification (same format as x)

  • color (str, optional) – Column name in data for color grouping. Creates different colors for each unique value in this column.

  • size (str, list, array, or None) – Column name or data for point/marker sizing (scatter plots)

  • shape (str, optional) – Column name in data for marker shape grouping (scatter plots)

  • facet_row (str, optional) – Column name in data for creating subplot rows. Each unique value in this column creates a separate row of subplots.

  • facet_col (str, optional) – Column name in data for creating subplot columns. Each unique value in this column creates a separate column of subplots.

  • base_plot (BasePlot, optional) – Existing Rekha plot to add to. If provided, this plot will be added to the existing plot’s axes instead of creating a new figure. This enables composition of multiple plot types while staying within the Rekha API.

  • title (str, optional) – Plot title text

  • labels (dict, optional) – Custom axis labels. Maps column names to display labels. Example: {'x_col': 'X Axis Label', 'y_col': 'Y Axis Label'}

  • dark_mode (bool, default False) –

    Whether to use dark theme. When True:

    • Uses dark background colors

    • Switches to light text and grid colors

    • Adjusts color palette for dark backgrounds

  • figsize (tuple, default (10, 6)) – Figure size as (width, height) in inches

  • title_font_size (float, default 16) – Font size for the plot title

  • label_font_size (float, default 14) – Font size for axis labels

  • tick_font_size (float, default 12) – Font size for axis tick labels

  • legend_font_size (float, default 12) – Font size for legend text

  • legend_loc (str, default 'best') – Legend location (‘best’, ‘upper right’, ‘upper left’, ‘lower left’, ‘lower right’, ‘right’, ‘center left’, ‘center right’, ‘lower center’, ‘upper center’, ‘center’)

  • grid (bool, default True) – Whether to show grid lines

  • grid_alpha (float, default 0.6) – Transparency of grid lines (0=invisible, 1=opaque)

  • grid_linewidth (float, default 0.5) – Width of grid lines in points

  • grayscale_friendly (bool, default False) –

    Whether to optimize for grayscale printing:

    • Uses patterns/hatching for differentiation

    • Increases contrast and line weights

    • Uses distinctive markers and line styles

  • color_mapping (dict, optional) – Custom mapping of category values to colors. Example: {'Category A': 'red', 'Category B': 'blue'}

  • category_order (list, optional) – Custom ordering for categorical data. Affects legend order and color assignment.

  • share_x (bool, default True) – Whether to share x-axis across facets. When True, all subplots will have the same x-axis range for easier comparison.

  • share_y (bool, default True) – Whether to share y-axis across facets. When True, all subplots will have the same y-axis range for easier comparison.

  • subplot_titles (bool, default True) – Whether to automatically generate titles for each subplot based on the faceting variables and their values.

  • col_wrap (int, optional) – Maximum number of columns before wrapping to a new row. Useful when faceting by a variable with many categories.

  • row_wrap (int, optional) – Maximum number of rows before wrapping to a new column. Useful when faceting by a variable with many categories.

  • subplot_spacing (float, default 0.3) – Spacing between subplots as a fraction of subplot size. Higher values create more space between plots.

  • margin_spacing (float, default 0.1) – Margin spacing around the entire figure as a fraction of figure size. Controls space for overall title and axis labels.

  • palette (str, default 'rekha') – Color palette to use. Options include ‘rekha’ (default), ‘pastel’, ‘bright’, ‘muted’, ‘colorblind’, etc.

  • xscale (str, optional) – X-axis scale type. Options: ‘linear’, ‘log’, ‘symlog’, ‘logit’. If None, uses matplotlib’s default (usually ‘linear’).

  • yscale (str, optional) – Y-axis scale type. Options: ‘linear’, ‘log’, ‘symlog’, ‘logit’. If None, uses matplotlib’s default (usually ‘linear’).

  • humanize_units (bool, default False) – Whether to format axis tick labels in human-readable form. For example, 1000000 becomes ‘1M’, 1500 becomes ‘1.5K’.

  • humanize_format (str, default 'intword') –

    Format style for humanized numbers:

    • ’intword’: Convert to words (1M, 2.5K)

    • ’intcomma’: Add commas (1,000,000)

    • ’scientific’: Scientific notation (1.0e6)

    • ’fractional’: Convert to fractions where applicable

  • rotate_xticks (bool or float, default False) –

    Whether to rotate x-axis tick labels:

    • False: No rotation (default)

    • True: Rotate 45 degrees

    • float: Rotate by specified degrees (e.g., 30, 45, 90)

  • alpha (float, optional) – Transparency level for plot elements (0=transparent, 1=opaque). Applies to bars, areas, markers, etc. depending on plot type.

  • label (str, optional) – Label for this data series in the legend. If provided, a legend will be automatically shown.

  • edgecolor (str, optional) – Color for edges of plot elements (bars, markers, etc.). Can be a color name, hex code, or RGB tuple.

  • linewidth (float, optional) – Width of lines or edges in points. Applies to different elements depending on plot type (e.g., bar edges, line plots, marker edges).

  • zorder (float, optional) – Drawing order for plot elements. Higher values are drawn on top. Useful for layering multiple plots.

  • **kwargs – Additional keyword arguments passed to the specific plot type. These are plot-specific and passed through to matplotlib functions.

Notes

This class handles the common initialization for all Rekha plots. Specific plot types add their own parameters and override methods as needed while maintaining this consistent base interface.

The color system automatically handles:

  • Categorical color mapping with consistent palettes

  • Dark/light theme switching

  • Grayscale printing optimization

  • Custom color overrides via color_mapping

update_layout(**kwargs)[source]¶

Update plot layout - matplotlib style.

Parameters:
  • title (str, optional) – Plot title

  • xlabel (str, optional) – X-axis label

  • ylabel (str, optional) – Y-axis label

  • xlim (tuple, optional) – X-axis limits

  • ylim (tuple, optional) – Y-axis limits

  • xscale (str, optional) – X-axis scale (‘linear’, ‘log’, ‘symlog’, ‘logit’)

  • yscale (str, optional) – Y-axis scale (‘linear’, ‘log’, ‘symlog’, ‘logit’)

add_annotation(text: str, x: float, y: float, **kwargs)[source]¶

Add annotation to the plot.

show()[source]¶

Display the plot in the current output (Jupyter notebook, script, etc.).

This method automatically handles layout optimization and displays the plot using matplotlib’s show() function. In Jupyter notebooks, the plot will appear inline. In scripts, it will open in a new window.

Notes

This method calls plt.tight_layout() before showing to ensure proper spacing of plot elements.

Examples

>>> import rekha as rk
>>> import pandas as pd
>>> df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
>>> fig = rk.line(df, x='x', y='y', title='Sample Plot')
>>> fig.show()  # Display the plot
get_axes()[source]¶

Get all axes from the figure.

Returns:

Always returns a list of axes objects for consistent API: - Single plots: list with one axes object - Faceted plots: flat list of all axes

Return type:

list of matplotlib.axes.Axes

Examples

>>> fig = rk.scatter(df, x='x', y='y')
>>> ax = fig.get_axes()[0]  # Get the single axes
>>> ax.set_title("Custom Title")
>>> fig = rk.scatter(df, x='x', y='y', facet_col='category')
>>> axes = fig.get_axes()  # List of all axes
>>> for ax in axes:
...     ax.grid(True)
save(filename: str, format: str = 'auto', transparent: bool | None = None, **kwargs)[source]¶

Save the plot to file with optimized settings for different use cases.

This method provides intelligent export options optimized for different contexts. It automatically adjusts resolution, format, and other settings based on the intended use case.

Parameters:
  • filename (str) – Output filename. Extension will be auto-added if not provided when using format presets.

  • format (str, default 'auto') –

    Export format preset with optimized settings:

    • ’web’: SVG with transparent background, perfect for websites and documentation. Vector format scales perfectly.

    • ’paper’: PDF with white background and high quality, ideal for academic papers and publications.

    • ’social’: High-resolution PNG (300 DPI) with transparent background by default, for social media, presentations, and online sharing.

    • ’presentation’: PNG optimized for slides with good balance of file size and quality.

    • ’auto’: Automatically detect format from file extension:

      • .svg → ‘web’ format

      • .pdf → ‘paper’ format

      • .png, .jpg, .jpeg → ‘social’ format

  • transparent (bool, optional) – Whether to use transparent background. If None (default), uses: - True for PNG formats (social, presentation) - True for SVG format (web) - False for PDF format (paper) - Can be overridden by setting explicitly

  • **kwargs – Additional parameters passed to matplotlib’s savefig(). These override the format preset defaults.

Examples

>>> import rekha as rk
>>> fig = rk.scatter(df, x='x', y='y')
>>>
>>> # Save for web (SVG with transparency)
>>> fig.save('plot.svg', format='web')
>>>
>>> # Save for academic paper (high-quality PDF)
>>> fig.save('figure1.pdf', format='paper')
>>>
>>> # Save for social media (high-res PNG with transparency)
>>> fig.save('chart.png', format='social')
>>>
>>> # Save with solid background
>>> fig.save('chart.png', format='social', transparent=False)
>>>
>>> # Auto-detect from extension
>>> fig.save('plot.png')  # Uses 'social' format with transparency
>>>
>>> # Custom settings with white background
>>> fig.save('plot.png', format='social', dpi=450, transparent=False)

Notes

The method automatically calls plt.tight_layout() before saving to ensure optimal spacing. Each format preset is optimized for its intended use case:

  • Web: Vector format, small file size, scales perfectly

  • Paper: High quality, white background, publication-ready

  • Social: High resolution, transparent by default for versatility

  • Presentation: Balanced quality and file size for slides

PNG files are saved with transparent backgrounds by default to provide maximum flexibility. Use transparent=False to get a solid background matching the theme (white for light mode, dark for dark mode).

save_all_formats(base_name: str, **kwargs)[source]¶

Save plot in all common formats for different use cases.

show_legend()[source]¶

Manually show the legend with appropriate styling.