plottools module

clabtoolkit.plottools.get_screen_size()[source]

Get the current screen size in pixels.

Returns:

Screen width and height in pixels (width, height).

Return type:

tuple of int

Examples

>>> width, height = get_screen_size()
>>> print(f"Screen size: {width}x{height}")
clabtoolkit.plottools.get_current_monitor_size()[source]

Get the size of the monitor where the mouse cursor is located.

clabtoolkit.plottools.estimate_monitor_dpi(screen_width, screen_height)[source]

Estimate monitor DPI based on screen resolution using common monitor configurations.

Parameters:
  • screen_width (int) – Screen width in pixels

  • screen_height (int) – Screen height in pixels

Returns:

Estimated DPI based on common monitor size/resolution combinations

Return type:

float

Examples

>>> estimate_monitor_dpi(1920, 1080)
96.0
>>>
>>> estimate_monitor_dpi(2560, 1440)
109.0
clabtoolkit.plottools.calculate_optimal_subplots_grid(num_views)[source]

Calculate optimal grid dimensions for a given number of views.

Parameters:

num_views (int) – Number of views to arrange.

Returns:

[rows, columns] for optimal grid layout.

Return type:

List[int]

Examples

>>> calculate_optimal_subplots_grid(4)
[2, 2]
>>>
>>> calculate_optimal_subplots_grid(6)
[2, 3]
>>>
>>> calculate_optimal_subplots_grid(1)
[1, 1]
clabtoolkit.plottools.calculate_subplot_layout(n_plots, screen_width=None, screen_height=None, target_aspect_ratio=None)[source]

Calculate optimal rows and columns for subplots based on screen proportions

Parameters:

n_plotsint

Number of subplots needed

screen_widthint, optional

Screen width in pixels (auto-detected if not provided)

screen_heightint, optional

Screen height in pixels (auto-detected if not provided)

target_aspect_ratiofloat, optional

Target aspect ratio (width/height). If provided, overrides screen detection

Returns:

tuple: (rows, cols, aspect_ratio_used)

clabtoolkit.plottools.create_proportional_subplots(n_plots, figsize_base=4, **layout_kwargs)[source]

Create a figure with subplots arranged according to screen proportions

Parameters:

n_plotsint

Number of subplots

figsize_basefloat

Base size for figure scaling

**layout_kwargs :

Additional arguments for calculate_subplot_layout()

Returns:

tuple: (fig, axes, layout_info)

clabtoolkit.plottools.calculate_font_sizes(plot_width, plot_height, screen_width=None, screen_height=None, colorbar_orientation='vertical', colorbar_width=None, colorbar_height=None, auto_detect_monitor=True)[source]

Calculate appropriate font sizes for matplotlib plots based on dimensions, monitor DPI, and colorbar configuration.

This function automatically scales font sizes for plot elements (title, axis labels, tick labels, colorbar title, and colorbar ticks) based on the plot dimensions, monitor characteristics, and colorbar orientation. The scaling ensures optimal readability across different plot sizes and display configurations by calculating monitor DPI from screen resolution.

The algorithm uses a reference plot size of 6×4 inches as a baseline and scales font sizes proportionally based on plot area and monitor DPI. Colorbar fonts are scaled independently based on colorbar dimensions and orientation constraints.

Parameters:
  • plot_width (float) – Width of the plot in inches. Must be positive. Typical values: 3-20 inches for scientific plots.

  • plot_height (float) – Height of the plot in inches. Must be positive. Typical values: 2-15 inches for scientific plots.

  • screen_width (int, optional) – Screen width in pixels, by default None. If None and auto_detect_monitor=True, automatically detected. Used together with screen_height to calculate monitor DPI.

  • screen_height (int, optional) – Screen height in pixels, by default None. If None and auto_detect_monitor=True, automatically detected. Used together with screen_width to calculate monitor DPI.

  • colorbar_orientation ({'vertical', 'horizontal'}, optional) – Orientation of the colorbar, by default ‘vertical’. - ‘vertical’: Colorbar positioned to the right/left of the plot - ‘horizontal’: Colorbar positioned above/below the plot

  • colorbar_width (float, optional) – Width of the colorbar in inches, by default None. If None, automatically calculated as 5% of plot width (vertical) or 80% of plot width (horizontal), with minimum constraints.

  • colorbar_height (float, optional) – Height of the colorbar in inches, by default None. If None, automatically calculated as 80% of plot height (vertical) or 5% of plot height (horizontal), with minimum constraints.

  • auto_detect_monitor (bool, optional) – Whether to automatically detect current monitor size, by default True. If False, uses fallback values when screen dimensions are not provided.

Returns:

Dictionary containing font sizes for different plot elements:

  • ’title’float

    Font size for the main plot title (8-28 pt range)

  • ’axis_labels’float

    Font size for axis labels (6-20 pt range)

  • ’tick_labels’float

    Font size for axis tick labels (6-20 pt range)

  • ’colorbar_title’float

    Font size for colorbar title (6-16 pt range, orientation-dependent)

  • ’colorbar_ticks’float

    Font size for colorbar tick labels (5-12 pt range, orientation-dependent)

  • ’_monitor_info’dict

    Debug information about monitor detection and DPI calculation

All font sizes are rounded to 1 decimal place.

Return type:

dict

Raises:
  • ValueError – If plot_width or plot_height are not positive numbers.

  • ValueError – If colorbar_orientation is not ‘vertical’ or ‘horizontal’.

  • TypeError – If numeric parameters are not of appropriate numeric types.

  • ImportError – If auto_detect_monitor=True but required packages (tkinter, screeninfo) are not available.

Examples

Basic usage with automatic monitor detection:

>>> fonts = calculate_font_sizes(6, 4)
>>> print(f"Title: {fonts['title']}, Colorbar title: {fonts['colorbar_title']}")
Title: 14.2, Colorbar title: 11.4

Specify monitor dimensions manually:

>>> fonts = calculate_font_sizes(6, 4, screen_width=2560, screen_height=1440)
>>> fonts['_monitor_info']['estimated_dpi']
109.0

Small subplot with horizontal colorbar on high-DPI display:

>>> fonts = calculate_font_sizes(3, 2,
...                             screen_width=3840, screen_height=2160,
...                             colorbar_orientation='horizontal')
>>> fonts['colorbar_title']  # Scaled up for high DPI
10.2

Disable auto-detection for headless environments:

>>> fonts = calculate_font_sizes(12, 8,
...                             screen_width=1920, screen_height=1080,
...                             auto_detect_monitor=False)
>>> fonts['title']
19.1

Custom colorbar dimensions:

>>> fonts = calculate_font_sizes(8, 6,
...                             colorbar_orientation='horizontal',
...                             colorbar_width=6.0,
...                             colorbar_height=0.5)

Apply to matplotlib plot:

>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(figsize=(6, 4))
>>> fonts = calculate_font_sizes(6, 4, colorbar_orientation='horizontal')
>>> ax.set_title('Brain Activation', fontsize=fonts['title'])
>>> ax.tick_params(labelsize=fonts['tick_labels'])
>>> # For colorbar:
>>> # cbar.set_label('Values', fontsize=fonts['colorbar_title'])
>>> # cbar.ax.tick_params(labelsize=fonts['colorbar_ticks'])

Notes

DPI Calculation and Scaling: 1. Automatically detects current monitor resolution using get_current_monitor_size() 2. Estimates monitor DPI based on resolution and common monitor configurations 3. Applies DPI-based scaling factor: scale = estimated_dpi / 96.0 (Windows standard) 4. Combines with plot area scaling for final font sizes

Font scaling algorithm: 1. Calculate plot area scaling factor relative to 6×4 inch reference 2. Calculate monitor DPI scaling factor relative to 96 DPI baseline 3. Scale colorbar fonts based on constraining dimension:

  • Vertical colorbars: limited by width → scale by width/0.5”

  • Horizontal colorbars: limited by height → scale by height/0.4”

  1. Apply orientation-specific bounds to ensure readability

The function prioritizes readability over exact proportional scaling, applying reasonable minimum and maximum font sizes for each element type.

Monitor configurations used for DPI estimation: - 1920×1080: 82-147 DPI (depending on screen size) - 2560×1440: 92-196 DPI - 3840×2160: 103-294 DPI - Other resolutions estimated using pixel density

For PyVista compatibility, convert results to integers: >>> pv_fonts = {k: int(round(v)) for k, v in fonts.items() if not k.startswith(‘_’)}

clabtoolkit.plottools.get_pyvista_fonts(plot_width, plot_height, **kwargs)[source]

Get integer font sizes specifically for PyVista compatibility.

Parameters:
  • plot_width (float) – Width of the plot in inches.

  • plot_height (float) – Height of the plot in inches.

  • **kwargs – Additional keyword arguments passed to calculate_font_sizes().

Returns:

Dictionary with integer font sizes suitable for PyVista (excludes debug info).

Return type:

dict

Examples

>>> fonts = get_pyvista_fonts(8, 6, colorbar_orientation='vertical')
>>> plotter.add_title('3D Brain', font_size=fonts['title'])

The plottools module provides low-level plotting infrastructure and layout calculation utilities that support visualization across the clabtoolkit package.

Key Features

  • Dynamic subplot grid calculation

  • Screen size detection and multi-monitor support

  • Optimal layout computation for complex visualizations

  • Monitor resolution detection

  • Flexible plotting utilities

Main Functions

Layout Calculation

  • calculate_optimal_subplots_grid(): Compute optimal subplot arrangements

  • calculate_subplot_layout(): Calculate subplot layout parameters

  • create_proportional_subplots(): Create proportional subplot grids

  • get_screen_size(): Detect screen dimensions for optimal figure sizing

  • get_current_monitor_size(): Get current monitor dimensions

Common Usage Examples

Dynamic subplot layout:

from clabtoolkit.plottools import calculate_optimal_subplots_grid
import matplotlib.pyplot as plt

# Calculate optimal grid for 8 subplots
rows, cols = calculate_optimal_subplots_grid(8)

fig, axes = plt.subplots(rows, cols, figsize=(12, 8))

# Use calculated layout
for i, ax in enumerate(axes.flat):
    if i < 8:  # Only plot actual data
        ax.plot([1, 2, 3], [1, 4, 2])
    else:  # Hide unused subplots
        ax.set_visible(False)

Screen-aware plotting:

# Get screen dimensions for optimal figure sizing
screen_width, screen_height = get_screen_size()

# Calculate figure size as proportion of screen
fig_width = screen_width * 0.8 / 100  # 80% of screen width in inches
fig_height = screen_height * 0.6 / 100  # 60% of screen height in inches

plt.figure(figsize=(fig_width, fig_height))

Proportional subplot creation:

# Create proportional subplots based on data
proportions = [2, 1, 3]  # Relative sizes
fig, axes = create_proportional_subplots(
    proportions=proportions,
    orientation='horizontal',
    figsize=(12, 6)
)

# Get current monitor size for optimal display
monitor_width, monitor_height = get_current_monitor_size()
print(f"Monitor: {monitor_width}x{monitor_height}")

# Calculate layout for multiple plots
layout = calculate_subplot_layout(
    n_plots=8,
    aspect_ratio=1.5
)