Skip to content

Single chart

daspi.plotlib.chart.SingleChart(source, target, feature='', *, hue='', dodge=False, shape='', size='', categorical_feature=False, target_on_y=True, colors=None, markers=None, n_size_bins=CATEGORY.N_SIZE_BINS, axes=None, **kwds)

Bases: Chart

Represents a basic chart visualization with customizable features.

This class provides a foundation for creating customizable chart visualizations. Customize the appearance and behavior of the chart using various parameters and keyword arguments.

PARAMETER DESCRIPTION
source

Pandas long format DataFrame containing the data source for the plot.

TYPE: pandas DataFrame

target

The target variable (column) to visualize.

TYPE: str

feature

The feature variable (column) to use for the visualization, by default ''

TYPE: str DEFAULT: ''

hue

The hue variable (column) for color differentiation, by default ''

TYPE: str DEFAULT: ''

dodge

Flag indicating whether to move overlapping categorical features with different colors along the axis so that they appear separately. Should only be set to True if given feature is categorical, by default False

TYPE: bool DEFAULT: False

shape

The categorical shape variable (column) for marker differentiation, by default ''.

TYPE: str DEFAULT: ''

size

The numeric variable (column) from which the marker size is derived. The range (minimum to maximum) of the variable is mapped to the marker size, by default ''

TYPE: str DEFAULT: ''

categorical_feature

Flag indicating whether the features are categorical. If True, the feature values are transferred to the feature axis and the major grid is removed. However, a minor grid is created so that the categories are visually better separated. This attribute is set to True if dodge is set to True, by default False.

TYPE: bool DEFAULT: False

target_on_y

Flag indicating whether the target variable is plotted on the y-axis, by default True

TYPE: bool DEFAULT: True

colors

Tuple of unique colors used for hue categories as hex or str, by default CATEGORY.PALETTE.

TYPE: Tuple[str, ...] | None DEFAULT: None

markers

Tuple of markers used for shape marker categories as strings, by default CATEGORY.MARKERS.

TYPE: Tuple[str, ...] DEFAULT: None

n_size_bins

Number of bins for the size range, by default CATEGORY.N_SIZE_BINS.

TYPE: int DEFAULT: N_SIZE_BINS

axes

An instance containing the subplots' Axes and their arrangement. All further keyword arguments from here on will only be considered if this one is not provided, by default None

TYPE: AxesFacets DEFAULT: None

**kwds

Additional key word arguments to instantiate the AxesFacets object.

DEFAULT: {}

sizing instance-attribute

A label handler for marker sizes based on the given size variable (column).

categorical_feature = categorical_feature or dodge instance-attribute

Flag indicating whether the features are categorical.

hue = hue instance-attribute

The hue variable (column) for color differentiation.

shape = shape instance-attribute

The categorical shape variable (column) for marker differentiation.

size = size instance-attribute

The numeric variable (column) from which the marker size is derived.

hueing = HueLabel(labels=(self.unique_labels(self.hue)), colors=(self._colors), follow_order=(style.follow_palette_order)) instance-attribute

A label handler for color differentiation based on the given hue variable column.

dodging = Dodger(dodge_categories, dodge_labels) instance-attribute

A handler for dodging categorical features along the axis.

shaping = ShapeLabel(self.unique_labels(self.shape), self._markers) instance-attribute

A label handler for marker shapes based on the given shape variable (column).

ax property

Gets the current Axes instance that is currently being worked on. This property raises an AttributeError if the current axis is not set. To access the current axis without errors but with the possibility of returning None, use the ax property of the AxesFacets instance (e.g. chart.axes.ax) (read-only).

variate_names property

Get names of all set variates (read-only).

color property

Get color for current variate (read-only).

marker property

Get marker for current variate (read-only)

sizes property

Get sizes for current variate, is set in grouped data generator (read-only).

legend_data property

Get dictionary of handles and labels (read-only). - keys: titles as str - values: handles and labels as tuple of tuples

axis_labels(feature_label, target_label)

Get the x and y axis labels based on the provided feature_label and target_label. - If a string is passed, it will be taken. - If True, labels of given feature or target name are used. - If False or None, empty string is used.

PARAMETER DESCRIPTION
feature_label

Flag or label for the feature variable.

TYPE: bool | str | None

target_label

Flag or label for the target variable.

TYPE: bool | str | None

RETURNS DESCRIPTION
Tuple[str, str]

A tuple containing the x-axis label (xlabel) and y-axis label (ylabel).

unique_labels(colname)

Get sorted unique elements of given column name if in source.

PARAMETER DESCRIPTION
colname

The name of the column in the source DataFrame.

TYPE: str

Returns:

Tuple: Sorted unique elements of the given column name.

update_variate(combination)

Update current variate by given combination coming from pandas DataFrame groupby function.

PARAMETER DESCRIPTION
combination

The combination of variables coming from the DataFrame groupby function.

TYPE: Any

dodge()

Converts the feature data to tick positions, taking dodging into account.

variate_data(skip_variate=[])

Generate grouped data if variate_names are set, otherwise yield the entire source DataFrame.

This method serves as a generator function that yields grouped data based on the variate_names attribute if it is set. If no variate_names are specified, it yields the entire source DataFrame.

PARAMETER DESCRIPTION
skip_variate

A list of variate names to skip during the grouping. If provided, these variates will not be included in the groupby operation. Default is []

TYPE: List[str] DEFAULT: []

Yields:

self._data : DataFrame Containing the grouped data or the entire source DataFrame.

plot(plotter, *, skip_variate=[], kw_call={}, kw_where={}, **kwds)

Apply a plotter with the specified data on the axis.

PARAMETER DESCRIPTION
plotter

The plotter object.

TYPE: Type[Plotter]

skip_variate

A list of variate names to skip during the grouping. If provided, these variates will not be included in the groupby operation. Default is []

TYPE: List[str] DEFAULT: []

kw_call

Additional keyword arguments for the plotter call method.

TYPE: Dict[str, Any] DEFAULT: {}

kw_where

Additional keyword arguments for the where method used to filter the data.

TYPE: Dict[str, Any] DEFAULT: {}

**kwds

Additional keyword arguments for the plotter object. Here you can set the plotter specific initialization parameters. You can also override the standard parameters color, marker, target_on_y, size (marker size) and width (for categorical feature plots). These parameters are handled automatically by the class. Only change them if you know what you are doing.

DEFAULT: {}

Returns:

Self: The SingleChart instance.

stripes(stripes=[], *, mean=False, median=False, control_limits=False, spec_limits=SpecLimits(), confidence=None, strategy='norm', agreement=6, **kwds)

Plot location and spread width lines, specification limits and/or confidence interval areas as stripes on each Axes. The location and spread (and their confidence bands) represent the data per axes.

PARAMETER DESCRIPTION
stripes

Additional non-predefined stripes to be added to the chart, by default [].

TYPE: List[Stripe] DEFAULT: []

mean

Whether to plot the mean value of the plotted data on the axes, by default False.

TYPE: bool DEFAULT: False

median

Whether to plot the median value of the plotted data on the axes, by default False.

TYPE: bool DEFAULT: False

control_limits

Whether to plot control limits representing the process spread, by default False.

TYPE: bool DEFAULT: False

spec_limits

If provided, specifies the specification limits. Default is SpecLimits(float('-inf'), float('inf')).

TYPE: SpecLimits DEFAULT: SpecLimits()

confidence

The confidence level between 0 and 1, by default None.

TYPE: float DEFAULT: None

strategy

Which strategy should be used to determine the control limits (process spread): - eval: The strategy is determined according to the given evaluate function. If none is given, the internal evaluate method is used. - fit: First, the distribution that best represents the process data is searched for and then the agreed process spread is calculated - norm: it is assumed that the data is subject to normal distribution. The variation tolerance is then calculated as agreement * standard deviation - data: The quantiles for the process variation tolerance are read directly from the data.

Default is 'norm'.

TYPE: (eval, fit, norm, data) DEFAULT: 'eval'

agreement

Specify the tolerated process variation for which the control limits are to be calculated. - If int, the spread is determined using the normal distribution agreementsigma, e.g. agreement = 6 -> 6sigma ~ covers 99.75 % of the data. The upper and lower permissible quantiles are then calculated from this. - If float, the value must be between 0 and 1.This value is then interpreted as the acceptable proportion for the spread, e.g. 0.9973 (which corresponds to ~ 6 sigma)

Default is 6 because SixSigma ;-)

TYPE: int or float DEFAULT: 6

**kwds

Additional keyword arguments for configuring StripesFacets.

DEFAULT: {}

RETURNS DESCRIPTION
SingleChart

The instance of the SingleChart with the specified stripes plotted on the axes.

TYPE: Self

Notes

This method plots stripes on the chart axes to represent statistical measures such as mean, median, control limits, and specification limits. The method provides options to customize the appearance and behavior of the stripes using various parameters and keyword arguments.

label(*, fig_title='', sub_title='', feature_label='', target_label='', info=False, feature_formatter=None, target_formatter=None, feature_angle=0.0, target_angle=0.0, feature_align='center', target_align='center')

Add labels and titles to the chart with advanced formatting options.

This method sets various labels and titles for the chart, including figure title, subtitle, axis labels, and provides extensive formatting control for tick labels including custom formatters, rotation angles, and alignment options.

PARAMETER DESCRIPTION
fig_title

The main title for the entire figure, displayed at the top in a larger font, by default ''.

TYPE: str DEFAULT: ''

sub_title

The subtitle for the entire figure, displayed below the main title in a smaller font, by default ''.

TYPE: str DEFAULT: ''

feature_label

The label for the feature variable axis, by default ''. If set to True, the feature variable name will be used. If set to False or None, no label will be added.

TYPE: str | bool DEFAULT: ''

target_label

The label for the target variable axis, by default ''. If set to True, the target variable name will be used. If set to False or None, no label will be added.

TYPE: str | bool DEFAULT: ''

info

Additional information to display on the chart. If True, the date and user information will be automatically added at the lower left corner of the figure. If a string is provided, it will be shown next to the date and user, separated by a comma. By default, no additional information is displayed.

TYPE: bool | str DEFAULT: False

feature_formatter

Formatter for the feature axis tick labels. Supports multiple input types for maximum flexibility:

  • String format templates: Simple format strings using Python's string formatting syntax (e.g., '{:.2f}', '{:.1e}', '${:.0f}', '{:.1%}')
  • Callable functions: Custom functions that take one or two arguments and return formatted strings
  • Matplotlib Formatters: Any matplotlib.ticker.Formatter instance for advanced formatting control
  • None: Use matplotlib's default formatting

The formatter automatically handles different orientations (target_on_y=True/False) and applies to the appropriate axis. By default, None.

TYPE: Formatter | Callable | str | None DEFAULT: None

target_formatter

Formatter for the target axis tick labels. Same options and behavior as feature_formatter. By default, None.

TYPE: Formatter | Callable | str | None DEFAULT: None

feature_angle

Rotation angle for feature axis tick labels in degrees. Positive values rotate counter-clockwise, negative values rotate clockwise. The chart automatically adjusts margins to accommodate rotated labels to prevent clipping. Common values: 0 (horizontal), 45 (diagonal), 90 (vertical). By default, 0.0 (no rotation).

TYPE: float DEFAULT: 0.0

target_angle

Rotation angle for target axis tick labels in degrees. Same behavior as feature_angle but for the target axis. By default, 0.0 (no rotation).

TYPE: float DEFAULT: 0.0

feature_align

Horizontal alignment for feature axis tick labels relative to their tick marks. 'center' aligns the label center with the tick, 'left' aligns the left edge, 'right' aligns the right edge. Particularly useful with rotated labels to achieve optimal positioning. By default, 'center'.

TYPE: (center, right, left) DEFAULT: 'center'

target_align

Alignment for target axis tick labels. For horizontal target axes, this controls horizontal alignment. For vertical target axes, this maps to vertical alignment: 'center' centers the label, 'left' maps to 'bottom', 'right' maps to 'top'. By default, 'center'.

TYPE: (center, right, left) DEFAULT: 'center'

RETURNS DESCRIPTION
SingleChart

The instance of the SingleChart with updated labels and titles for method chaining.

Examples:

Basic labeling:

chart.label(
    fig_title='Temperature Analysis',
    sub_title='Daily measurements',
    feature_label='Time (hours)',
    target_label='Temperature (°C)',
    info='Data collected in laboratory conditions'
)

String formatter examples:

# Scientific notation
chart.label(
    feature_formatter='{:.2e}',  # 1.23e+03
    target_formatter='{:.1f}'    # 123.5
)

# Currency and percentage formatting
chart.label(
    feature_formatter='${:.0f}',  # $1234
    target_formatter='{:.1%}'     # 12.3%
)

Custom callable formatters:

# Temperature formatter
def temp_formatter(value):
    return f"{value:.1f}°C"

# Business formatter with units
def business_formatter(value, pos=None):
    if value >= 1000000:
        return f'{value/1000000:.1f}M'
    elif value >= 1000:
        return f'{value/1000:.1f}K'
    return f'{value:.0f}'

chart.label(
    target_formatter=temp_formatter,
    feature_formatter=business_formatter
)

Rotation and alignment for crowded labels:

# Diagonal labels with right alignment
chart.label(
    feature_angle=45,
    feature_align='right',
    target_angle=0,
    target_align='center'
)

# Vertical labels for long category names
chart.label(
    feature_angle=90,
    feature_align='center'
)

Combined advanced formatting:

chart.label(
    fig_title='Sales Performance Q3 2024',
    sub_title='Revenue by Product Category',
    feature_label='Product Categories',
    target_label='Revenue',
    feature_formatter=lambda x: x.title(),  # Capitalize categories
    target_formatter='${:,.0f}',           # Currency with commas
    feature_angle=30,                      # Slight rotation
    feature_align='right',                 # Right-align for rotation
    info='Data from sales database'
)
Notes
  • String formatters use Python's string formatting syntax and are automatically converted to matplotlib-compatible formatters
  • The chart automatically adjusts margins when using rotated labels to prevent clipping
  • Formatters and angles are applied based on the chart orientation (target_on_y parameter)
  • All formatting options work consistently across different plot types