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:
|
target
|
The target variable (column) to visualize.
TYPE:
|
feature
|
The feature variable (column) to use for the visualization, by default ''
TYPE:
|
hue
|
The hue variable (column) for color differentiation, by default ''
TYPE:
|
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:
|
shape
|
The categorical shape variable (column) for marker differentiation, by default ''.
TYPE:
|
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:
|
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
TYPE:
|
target_on_y
|
Flag indicating whether the target variable is plotted on the y-axis, by default True
TYPE:
|
colors
|
Tuple of unique colors used for hue categories as hex or str,
by default
TYPE:
|
markers
|
Tuple of markers used for shape marker categories as strings,
by default
TYPE:
|
n_size_bins
|
Number of bins for the size range, by default
TYPE:
|
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:
|
**kwds
|
Additional key word arguments to instantiate the
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:
|
target_label
|
Flag or label for the target variable.
TYPE:
|
| 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:
|
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:
|
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:
|
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:
|
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:
|
kw_call
|
Additional keyword arguments for the plotter call method.
TYPE:
|
kw_where
|
Additional keyword arguments for the where method used to filter the data.
TYPE:
|
**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:
|
mean
|
Whether to plot the mean value of the plotted data on the axes, by default False.
TYPE:
|
median
|
Whether to plot the median value of the plotted data on the axes, by default False.
TYPE:
|
control_limits
|
Whether to plot control limits representing the process spread, by default False.
TYPE:
|
spec_limits
|
If provided, specifies the specification limits. Default is SpecLimits(float('-inf'), float('inf')).
TYPE:
|
confidence
|
The confidence level between 0 and 1, by default None.
TYPE:
|
strategy
|
Which strategy should be used to determine the control
limits (process spread):
- Default is 'norm'.
TYPE:
|
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:
|
**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:
|
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:
|
sub_title
|
The subtitle for the entire figure, displayed below the main title in a smaller font, by default ''.
TYPE:
|
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:
|
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:
|
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:
|
feature_formatter
|
Formatter for the feature axis tick labels. Supports multiple input types for maximum flexibility:
The formatter automatically handles different orientations (target_on_y=True/False) and applies to the appropriate axis. By default, None.
TYPE:
|
target_formatter
|
Formatter for the target axis tick labels. Same options and behavior as feature_formatter. By default, None.
TYPE:
|
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:
|
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:
|
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:
|
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:
|
| 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