Agent Helper Utilities¶
AI-focused utilities for creating consistent, high-quality visualizations. This module provides helper functions organized into submodules designed to assist AI agents and automation tools in generating professional charts.
Note
The helpers module was previously named agent_utils in versions before 0.2.0.
The old name is available as a deprecated alias for backward compatibility.
Overview¶
The helpers module is organized into specialized submodules:
data: Data validation and cleaning utilities
colors: Automatic color selection and management
formatting: Axis labels, legends, and annotations
quality: Quality checks and chart suggestions
io: Figure creation and saving utilities
Main Module¶
Agent utility functions for dartwork-mpl.
Helper functions to assist AI agents in creating consistent, high-quality visualizations.
This module is organized into submodules: - data: Data validation and cleaning - colors: Color selection and management - formatting: Axis labels, legends, and annotations - quality: Quality checks and suggestions - io: Figure creation and saving
- dartwork_mpl.helpers.add_value_labels(ax: Axes, x: ndarray, y: ndarray, format_str: str = '.1f', offset_y: float = 0.02, color: str | None = None, fontsize: float | None = None) None[source]¶
Add value labels to data points.
- Parameters:
ax (Axes) – Matplotlib axes
x (np.ndarray) – X coordinates
y (np.ndarray) – Y values to label
format_str (str) – Format string for values
offset_y (float) – Vertical offset as fraction of y-range
color (str | None) – Text color (defaults to “oc.gray7”)
fontsize (int | None) – Font size (defaults to fs(-1))
Examples
>>> add_value_labels(ax, quarters, revenue, format_str=".0f")
- dartwork_mpl.helpers.auto_select_colors(n_series: int, color_type: Literal['categorical', 'sequential', 'diverging'] = 'categorical', highlight_index: int | None = None) list[str][source]¶
Automatically select appropriate colors for data series.
- Parameters:
n_series (int) – Number of data series
color_type (str) – Type of color scheme to use
highlight_index (int | None) – Index of series to highlight
- Returns:
List of dartwork color names
- Return type:
list[str]
Examples
>>> colors = auto_select_colors(5, "categorical") >>> colors = auto_select_colors(3, highlight_index=0)
- dartwork_mpl.helpers.check_figure_quality(fig: Figure) list[str][source]¶
Check figure for common quality issues.
- Parameters:
fig (Figure) – Figure to check
- Returns:
List of issues found
- Return type:
list[str]
Examples
>>> issues = check_figure_quality(fig) >>> if issues: ... print("Quality issues found:") ... for issue in issues: ... print(f" - {issue}")
- dartwork_mpl.helpers.create_figure_with_style(style: str = 'report-kr', figsize: tuple[float, float] | None = None, dpi: int = 200) Figure[source]¶
Create a figure with dartwork style pre-applied.
- Parameters:
style (str) – Style preset name
figsize (tuple[float, float] | None) – Figure size (defaults to DW x DW*0.6)
dpi (int) – Figure DPI
- Returns:
Configured figure
- Return type:
Figure
Examples
>>> fig = create_figure_with_style("scientific")
- dartwork_mpl.helpers.format_axis_labels(ax: Axes, x_label: str | None = None, y_label: str | None = None, x_unit: str | None = None, y_unit: str | None = None, title: str | None = None) None[source]¶
Apply consistent formatting to axis labels.
- Parameters:
ax (Axes) – Matplotlib axes
x_label (str | None) – X-axis label
y_label (str | None) – Y-axis label
x_unit (str | None) – Unit for x-axis (will be appended in parentheses)
y_unit (str | None) – Unit for y-axis (will be appended in parentheses)
title (str | None) – Axes title
Examples
>>> format_axis_labels(ax, "Time", "Revenue", x_unit="Quarter", y_unit="억원")
- dartwork_mpl.helpers.optimize_legend(ax: Axes, preferred_loc: str = 'best', max_cols: int = 3, outside: bool = False) None[source]¶
Optimize legend placement and formatting.
- Parameters:
ax (Axes) – Matplotlib axes
preferred_loc (str) – Preferred location if space permits
max_cols (int) – Maximum number of columns for legend
outside (bool) – Whether to place legend outside plot area
Examples
>>> optimize_legend(ax, preferred_loc="upper right") >>> optimize_legend(ax, outside=True)
- dartwork_mpl.helpers.save_figure(fig: Figure, filename: str | Path, formats: tuple[str, ...] = ('png',), dpi: int = 300, create_dir: bool = True, verbose: bool = True) None[source]¶
Save figure with consistent settings.
- Parameters:
fig (Figure) – Matplotlib figure
filename (str | Path) – Output filename (without extension)
formats (tuple[str, ...]) – Output formats
dpi (int) – Resolution for raster formats
create_dir (bool) – Whether to create output directory if missing
verbose (bool) – Whether to print confirmation
Examples
>>> save_figure(fig, "output/chart", formats=("png", "svg"))
- dartwork_mpl.helpers.suggest_chart_type(x_type: str, y_type: str | None, n_points: int, n_series: int = 1) str[source]¶
Suggest appropriate chart type based on data characteristics.
- Parameters:
x_type (str) – Type of x data: “continuous”, “categorical”, “temporal”
y_type (str | None) – Type of y data: “continuous”, “categorical”, “count”, None
n_points (int) – Number of data points
n_series (int) – Number of data series
- Returns:
Suggested chart type
- Return type:
str
Examples
>>> chart_type = suggest_chart_type("categorical", "continuous", 5, 1) >>> print(chart_type) # "bar"
- dartwork_mpl.helpers.validate_data(x: Any, y: Any | None = None, require_same_length: bool = True, allow_nan: bool = False, min_points: int = 2) tuple[ndarray, ndarray | None][source]¶
Validate and clean input data for plotting.
- Parameters:
x (Any) – X-axis data
y (Any | None) – Y-axis data (optional for histograms, etc.)
require_same_length (bool) – Whether x and y must have the same length
allow_nan (bool) – Whether to allow NaN values
min_points (int) – Minimum number of data points required
- Returns:
Cleaned x and y arrays
- Return type:
tuple[np.ndarray, np.ndarray | None]
- Raises:
ValueError – If validation fails
Examples
>>> x, y = validate_data([1, 2, 3], [4, 5, 6]) >>> x_clean, _ = validate_data([1, 2, np.nan, 4], allow_nan=False)
Data Validation¶
Utilities for validating and cleaning data before plotting.
Data validation and cleaning utilities for dartwork-mpl agents.
This module provides functions for validating and cleaning data before plotting.
- dartwork_mpl.helpers.data.validate_data(x: Any, y: Any | None = None, require_same_length: bool = True, allow_nan: bool = False, min_points: int = 2) tuple[ndarray, ndarray | None][source]¶
Validate and clean input data for plotting.
- Parameters:
x (Any) – X-axis data
y (Any | None) – Y-axis data (optional for histograms, etc.)
require_same_length (bool) – Whether x and y must have the same length
allow_nan (bool) – Whether to allow NaN values
min_points (int) – Minimum number of data points required
- Returns:
Cleaned x and y arrays
- Return type:
tuple[np.ndarray, np.ndarray | None]
- Raises:
ValueError – If validation fails
Examples
>>> x, y = validate_data([1, 2, 3], [4, 5, 6]) >>> x_clean, _ = validate_data([1, 2, np.nan, 4], allow_nan=False)
Example:
import dartwork_mpl as dm
import numpy as np
# Validate data before plotting
x = np.array([1, 2, np.nan, 4, 5])
y = np.array([2, 4, 6, 8, 10])
x_clean, y_clean = dm.helpers.data.validate_data(
x, y,
require_same_length=True,
allow_nan=False,
min_points=3
)
Color Selection¶
Automatic color palette selection based on data characteristics.
Color selection and management utilities for dartwork-mpl agents.
This module provides functions for automatic color selection and color scheme management.
- dartwork_mpl.helpers.colors.auto_select_colors(n_series: int, color_type: Literal['categorical', 'sequential', 'diverging'] = 'categorical', highlight_index: int | None = None) list[str][source]¶
Automatically select appropriate colors for data series.
- Parameters:
n_series (int) – Number of data series
color_type (str) – Type of color scheme to use
highlight_index (int | None) – Index of series to highlight
- Returns:
List of dartwork color names
- Return type:
list[str]
Examples
>>> colors = auto_select_colors(5, "categorical") >>> colors = auto_select_colors(3, highlight_index=0)
Example:
import dartwork_mpl as dm
# Auto-select colors for 5 data series
colors = dm.helpers.colors.auto_select_colors(
n_series=5,
color_type='qualitative',
highlight_index=0 # Highlight first series
)
# Plot with auto-selected colors
for i, color in enumerate(colors):
ax.plot(x, data[i], color=color, label=f"Series {i+1}")
Formatting Utilities¶
Functions for formatting axes, legends, and annotations.
Formatting utilities for axes, legends, and annotations.
This module provides functions for formatting matplotlib elements to maintain consistency in visualizations.
- dartwork_mpl.helpers.formatting.add_value_labels(ax: Axes, x: ndarray, y: ndarray, format_str: str = '.1f', offset_y: float = 0.02, color: str | None = None, fontsize: float | None = None) None[source]¶
Add value labels to data points.
- Parameters:
ax (Axes) – Matplotlib axes
x (np.ndarray) – X coordinates
y (np.ndarray) – Y values to label
format_str (str) – Format string for values
offset_y (float) – Vertical offset as fraction of y-range
color (str | None) – Text color (defaults to “oc.gray7”)
fontsize (int | None) – Font size (defaults to fs(-1))
Examples
>>> add_value_labels(ax, quarters, revenue, format_str=".0f")
- dartwork_mpl.helpers.formatting.format_axis_labels(ax: Axes, x_label: str | None = None, y_label: str | None = None, x_unit: str | None = None, y_unit: str | None = None, title: str | None = None) None[source]¶
Apply consistent formatting to axis labels.
- Parameters:
ax (Axes) – Matplotlib axes
x_label (str | None) – X-axis label
y_label (str | None) – Y-axis label
x_unit (str | None) – Unit for x-axis (will be appended in parentheses)
y_unit (str | None) – Unit for y-axis (will be appended in parentheses)
title (str | None) – Axes title
Examples
>>> format_axis_labels(ax, "Time", "Revenue", x_unit="Quarter", y_unit="억원")
- dartwork_mpl.helpers.formatting.optimize_legend(ax: Axes, preferred_loc: str = 'best', max_cols: int = 3, outside: bool = False) None[source]¶
Optimize legend placement and formatting.
- Parameters:
ax (Axes) – Matplotlib axes
preferred_loc (str) – Preferred location if space permits
max_cols (int) – Maximum number of columns for legend
outside (bool) – Whether to place legend outside plot area
Examples
>>> optimize_legend(ax, preferred_loc="upper right") >>> optimize_legend(ax, outside=True)
Example:
import dartwork_mpl as dm
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(x, y)
# Format axis labels automatically
dm.helpers.formatting.format_axis_labels(
ax,
xlabel="Time",
ylabel="Value",
use_latex=False
)
# Optimize legend placement
dm.helpers.formatting.optimize_legend(
ax,
loc='best',
frameon=False
)
# Add value labels to data points
dm.helpers.formatting.add_value_labels(
ax,
x, y,
format_str="{:.1f}",
offset=(0, 5)
)
Quality Checks¶
Functions for checking figure quality and suggesting improvements.
Quality checks and chart type suggestions for dartwork-mpl agents.
This module provides functions for checking figure quality and suggesting appropriate chart types based on data characteristics.
- dartwork_mpl.helpers.quality.check_figure_quality(fig: Figure) list[str][source]¶
Check figure for common quality issues.
- Parameters:
fig (Figure) – Figure to check
- Returns:
List of issues found
- Return type:
list[str]
Examples
>>> issues = check_figure_quality(fig) >>> if issues: ... print("Quality issues found:") ... for issue in issues: ... print(f" - {issue}")
- dartwork_mpl.helpers.quality.suggest_chart_type(x_type: str, y_type: str | None, n_points: int, n_series: int = 1) str[source]¶
Suggest appropriate chart type based on data characteristics.
- Parameters:
x_type (str) – Type of x data: “continuous”, “categorical”, “temporal”
y_type (str | None) – Type of y data: “continuous”, “categorical”, “count”, None
n_points (int) – Number of data points
n_series (int) – Number of data series
- Returns:
Suggested chart type
- Return type:
str
Examples
>>> chart_type = suggest_chart_type("categorical", "continuous", 5, 1) >>> print(chart_type) # "bar"
Example:
import dartwork_mpl as dm
# Check figure quality
issues = dm.helpers.quality.check_figure_quality(fig)
if issues:
print("Quality issues found:")
for issue in issues:
print(f" - {issue}")
# Get chart type suggestions
suggested_type = dm.helpers.quality.suggest_chart_type(
x_data=x,
y_data=y,
data_type='continuous'
)
print(f"Suggested chart type: {suggested_type}")
I/O Utilities¶
Functions for creating and saving figures with proper settings.
Figure creation and I/O utilities for dartwork-mpl agents.
This module provides functions for creating and saving figures with consistent settings.
- dartwork_mpl.helpers.io.create_figure_with_style(style: str = 'report-kr', figsize: tuple[float, float] | None = None, dpi: int = 200) Figure[source]¶
Create a figure with dartwork style pre-applied.
- Parameters:
style (str) – Style preset name
figsize (tuple[float, float] | None) – Figure size (defaults to DW x DW*0.6)
dpi (int) – Figure DPI
- Returns:
Configured figure
- Return type:
Figure
Examples
>>> fig = create_figure_with_style("scientific")
- dartwork_mpl.helpers.io.save_figure(fig: Figure, filename: str | Path, formats: tuple[str, ...] = ('png',), dpi: int = 300, create_dir: bool = True, verbose: bool = True) None[source]¶
Save figure with consistent settings.
- Parameters:
fig (Figure) – Matplotlib figure
filename (str | Path) – Output filename (without extension)
formats (tuple[str, ...]) – Output formats
dpi (int) – Resolution for raster formats
create_dir (bool) – Whether to create output directory if missing
verbose (bool) – Whether to print confirmation
Examples
>>> save_figure(fig, "output/chart", formats=("png", "svg"))
Example:
import dartwork_mpl as dm
# Create figure with style applied
fig, ax = dm.helpers.io.create_figure_with_style(
style='scientific',
figsize=(8, 6),
dpi=100
)
# Plot your data
ax.plot(x, y)
# Save with optimal settings
dm.helpers.io.save_figure(
fig,
filename='output.png',
dpi=300,
transparent=False,
optimize=True
)
Integration with AI Agents¶
The helpers module is designed to be easily used by AI agents and automation tools:
import dartwork_mpl as dm
import matplotlib.pyplot as plt
def ai_create_chart(data, chart_type=None):
"""Example function an AI agent might use."""
# Validate input data
x, y = dm.helpers.data.validate_data(data['x'], data['y'])
# Suggest chart type if not specified
if chart_type is None:
chart_type = dm.helpers.quality.suggest_chart_type(x, y)
# Create figure with appropriate style
fig, ax = dm.helpers.io.create_figure_with_style(
style='scientific' if chart_type == 'scatter' else 'web'
)
# Auto-select colors
colors = dm.helpers.colors.auto_select_colors(
n_series=1,
color_type='sequential' if chart_type == 'line' else 'qualitative'
)
# Create the plot
if chart_type == 'line':
ax.plot(x, y, color=colors[0])
elif chart_type == 'scatter':
ax.scatter(x, y, color=colors[0])
# Format and optimize
dm.helpers.formatting.format_axis_labels(ax)
dm.helpers.formatting.optimize_legend(ax)
# Check quality
issues = dm.helpers.quality.check_figure_quality(fig)
return fig, issues
See Also¶
AI-Assisted Development - Guide for using dartwork-mpl with AI tools
MCP Server - MCP server for AI integration
Quick Start - Getting started with dartwork-mpl