XY: Scatterplots including Time Series

View source: R/XY.R

XYR Documentation

Scatterplots including Time Series

Description

lessR introduces the concept of an analytic view visualization function, in which the choice of visualization function directly reflects the structure of the data and the analyst's intent for understanding the data. The function XY() visualizes the joint distribution of two continuous variables, or more generally the relationship among multiple variables, along with associated summary statistics. The specific representation is selected with the form argument:

  • Scatterplot of points with form="scatter" (default)

  • Contour plot (2-dimensional density display) with form="contour"

  • Smoothed scatterplot with form="smooth"

  • Hexbin scatterplot with form="hexbin"

  • Sunflower plot, one petal for each point per coincident observation, with form="sunflower"

Where permissible, stratification divides the data into groups via the arguments by and facet. The by argument overlays groups in a single coordinate system for direct comparison, while facet produces coordinated small multiples on separate panels. XY() requires continuous x and y. When the continuous x is ordered in time, such as a date or an equal-interval sequence, successive points are connected to form a time-series display. Relationships between two categorical variables, such as bubble plots, are instead handled by Chart with form="bubble" and a by variable.

When running in RStudio, static graphics are drawn in the Plots window. When the default use_plotly=TRUE, the interactive plotly version of the scatterplot (including time series) display is also drawn in the Viewer window.

A scatterplot displays the joint values of one or more variables as points in an \(n\)-dimensional coordinate system, in which the coordinates of each point are the values of \(n\) variables for a single observation (row of data). With a common syntax, XY(x, y, ...) generates a family of related 1- or 2-dimensional relationship plots, possibly enhanced with fitted lines, ellipses, and outlier labeling. Categorical variables should typically be defined as factors, and date variables should be stored as Date objects. When x is of class Date, the display is treated as a time-indexed series.

XY() therefore serves as the relationship-oriented counterpart to Chart() (aggregated values) and X() (univariate distributions) within the three-function visualization framework implemented in lessR.

Usage

XY(

    # -------------------------------------------------------
    # Data from which to construct the plot for x- and y-axis
    x, y, data=d, filter=NULL,

    # ----------------------------------------------------
    # Stratification: Same (by) or separate panels (facet)
    by=NULL,
    facet=NULL, n_row=NULL, n_col=NULL, aspect="fill",

    # -----------------------------------
    # Geometric forms of relational plots
    form=c("scatter", "smooth", "contour", "hexbin", "sunflower"),


    # -------------------------------
    # Enhancements and customizations
    # -------------------------------

    # --------------------------------------------------------------------
    # Analogy of physical Marks on paper that create the points and labels
    # See  ?style  for more options with the  style()  function
    theme=getOption("theme"),
    fill=NULL, color=NULL,
    transparency=getOption("trans_pt_fill"),

    # -----------------------------------------------
    # Plotted points and any connecting line segments
    enhance=FALSE, means=TRUE,
    pt_size=NULL, pt_size_cut=NULL, pt_shape="circle", line_width=1.5,
    segments=FALSE,

    # ----------------------
    # Sort and jitter points
    sort=c("0", "-", "+"),
    jitter_x=NULL, jitter_y=NULL,

    # ----------------
    # Outlier analysis
    ID="row.name", ID_size=0.60,
    MD_cut=0, out_cut=0, out_shape="circle", out_size=1,

    # -------------------------------------------------
    # Fit line, confidence interval, confidence ellipse
    fit=c("off", "loess", "lm", "ls", "null", "exp", "quad",
          "power", "log"),
    fit_power=1, fit_se=0.95, fit_span_loess=0.75, fit_degree_loess=2, 
    fit_color=getOption("fit_color"), fit_lwd=getOption("fit_lwd"),
    fit_new=NULL, fit_errors=FALSE, ellipse=0,
    ellipse_fill=getOption("ellipse_fill"),
    ellipse_color=getOption("ellipse_color"),
    ellipse_lwd=getOption("ellipse_lwd"),

    # -----------------------------------------------------------------------
    # Time series and forecasting, plot x values sequentially [xDate, y or Y]
    ts_unit=NULL, ts_ahead=0, ts_method=c("es", "lm"),
    ts_source=c("fable", "classic"), ts_agg=c("sum", "mean"),
    ts_NA=NULL, ts_format=NULL, ts_fitted=FALSE, ts_PI=.95, 
    ts_trend=NULL, ts_seasons=NULL, ts_error=NULL, 
    ts_alpha=NULL, ts_beta=NULL, ts_gamma=NULL, ts_new_x=NULL,
    ts_stack=FALSE, ts_area_fill="transparent", ts_area_split=0,
    ts_n_x_tics=NULL,
    # Run chart (indicate with .index for the name of the x-variable)
    show_runs=FALSE, center_line=c("off", "mean", "median", "zero"),

    # -----------
    # Bubble plot [xCategorical, or xCategorical and yCategorical]
    radius=NULL, power=0.5, low_fill=NULL, hi_fill=NULL,

    # -----------------------------------------------------------
    # Large data sets, smoothing, contours and binning  [x and y]
    smooth_points=100, smooth_size=1,
    smooth_power=0.25, smooth_bins=128, hex_bins=30, hexbin_legend=TRUE,
    n_bins=1,
    contour_n=20, contour_nbins=50, contour_points=FALSE,
    contour_legend=FALSE,

    # -----------------------------
    # Bins for a frequency polygon
    bin=FALSE, bin_start=NULL, bin_width=NULL, bin_end=NULL,
    breaks="Sturges", cumulate=FALSE,


    # ----------------------
    # Axes labels and values
    # ----------------------

    # -----------------------
    # Axis labels and spacing
    xlab=NULL, ylab=NULL, main=NULL, sub=NULL,
    label_adjust=c(0,0), margin_adjust=c(0,0,0,0),  # top, right, bottom, left
    pad_x=c(0,0), pad_y=c(0,0),

    # ---------------------
    # Axis values specified
    scale_x=NULL, scale_y=NULL, origin_x=NULL, origin_y=NULL,

    # ---------------------
    # Axis values formatted
    rotate_x=getOption("rotate_x"), rotate_y=getOption("rotate_y"),
    offset=getOption("offset"),
    axis_fmt=c("K", ",", ".", ""), axis_x_prefix="", axis_y_prefix="",
    font_size=1,
    xy_ticks=TRUE, n_axis_x_skip=0, n_axis_y_skip=0, 

    # ------
    # legend
    legend_title=NULL,


    # -------------
    # Miscellaneous
    # -------------

    # ----------------------------------------------------
    # Add one or more objects, text, or geometric figures
    add=NULL, x1=NULL, y1=NULL, x2=NULL, y2=NULL,

    # ---------------------------------------------
    # Output: turn off, to PDF file, decimal digits
    quiet=getOption("quiet"), do_plot=TRUE,
    use_plotly=getOption("lessR.use_plotly"),
    pdf_file=NULL, width=6.5, height=6,
    digits_d=NULL,

    # ---------------------------------
    # Other
    eval_df=NULL, fun_call=NULL,

    # -------------------------------------------------------------
    # Deprecated, to be removed in future versions
    smooth=FALSE,
    stat=c("mean", "sum", "sd", "deviation", "min", "median", "max"),
    stat_x=c("count", "proportion", "%"),
    type=NULL, size=NULL, shape=NULL, plot_errors=NULL, span=NULL,
    segments_x=NULL, segments_y=NULL)

Arguments

x

The variable plotted on the x-axis. The data values are continuous, either cross-sectional or a time series. If x is sorted with equal intervals separating the values, or is a time series, then by default the points are plotted sequentially and connected with line segments. If named .index, a run chart is generated from the corresponding y variable. If named .normal, .lognormal, .exponential or .uniform, the quantile-quantile chart of that distribution is generated from the corresponding y variable. Each of these keywords names no variable, so each is matched without regard to case: .index or .Index, .normal or .NORMAL. Can specify multiple x-variables or multiple y-variables as vectors, but not both.

y

The continuous variable plotted on the vertical y-axis.

data

Data frame that contains one or both of x and y. Default data frame is d. Specify NULL if the variables for the analysis are in the global environment instead.

filter

A logical expression or a vector of integers that specify the row numbers to retain, defining a subset of rows of the data frame to analyze.


by

A grouping variable, a categorical variable that provides separate group profiles of the primary numeric variables x and y on the same plot. Only one by variable is permitted, as the resulting visual clutter compromises interpretability. Stratification by by applies only to a scatter plot, form="scatter", not to the "smooth", "contour", and "hexbin" forms.

facet

One categorical variable, or a vector of two categorical variables, providing a separate plot of the primary variable(s) x and y for each level of the variable or combination of two levels. Stratification by facet applies to the "scatter", "smooth", "contour", and "hexbin" forms, each panel sharing a common scale so that the panels are directly comparable.
When x (or y) is a vector of variables, the multi-series overlay is repeated across the panels, such as XY(c(Pre, Post), Salary, facet=Gender): each panel displays the full overlay for one level of the facet variable.

n_row

Optional specification for the number of rows in the facet layout, a multi-panel display. Specify n_col or n_row, but not both.

n_col

Optional specification for the number of columns in the facet layout. Specify n_col or n_row, but not both. The default is 1.

aspect

Aspect ratio (height/width) of the panels, applied only to the lattice facet forms: scatter and hexbin. The default "fill" expands each panel to occupy the available space (here "fill" refers to filling space, not to the fill color argument). Set to 1 for square panels, "iso" to give both axes the same scale in physical units, or "xy" to bank line slopes toward an effective 45 degrees. A faceted quantile-quantile chart defaults to "iso" rather than to "fill", so that its 45-degree reference line is drawn at 45 degrees. The base-R contour and smooth facets size their panels automatically and ignore aspect.


form

The plotted geometric form. The default is "scatter" for a scatter plot. To summarize the bivariate density for two numeric variables, set to "smooth" for a smoothed density plot, "hexbin" for a hexbin plot, or "contour" for a contour plot. Set to "sunflower" for a sunflower plot, in which each plotted point carries one petal for each observation at that coordinate, so that coincident observations remain visible. Because petals appear only where observations coincide, the form applies to discrete or rounded data, such as integer counts or rating scales; with continuous data that yields no repeated pairs, every point is drawn as a single dot. The single-panel display is rendered by base R sunflowerplot; facet draws the petals in a lattice panel instead, one set of coordinates and so one petal count per panel. by does not apply: overlaid groups would interleave their petals at a shared coordinate, leaving no count to read. To stratify within a single panel, use "hexbin".


theme

Color theme for this analysis. Make persistent across analyses with style.

fill

Fill color for the points. Can also be set via the lessR function getColors to select from a variety of color palettes. For points, the default is pt_fill; for the area under a line chart, violin_fill. For a line chart, set to "on" to use the default color.

color

Border color of the points or line color for a line plot. Can be a vector to customize the color for each point or a color range such as "blues" (see getColors). Default is pt_color from the lessR style function.

transparency

Transparency factor of the fill color of each point. Default is trans_pt_fill from the lessR style function, which is 0.1 for points. Bubbles have a default transparency of 0.4.


enhance

For a two-variable scatterplot, if TRUE, automatically add the 0.95 data ellipse, labels for outliers beyond a squared Mahalanobis distance of 6 from the ellipse center, the least squares line for all data, the least squares line for the data excluding outliers, and horizontal and vertical lines representing the means of the two variables.

means

If one variable is categorical (factor) and the other is continuous, then if TRUE the group means are plotted in the scatterplot by default. Also applies to a 1-D scatterplot.

pt_size

When set to a constant, the scaling factor for standard points (not bubbles) or for a line, with default of 1.0 for points and 2.0 for a line. Set to 0 to suppress plotting of points. If ts_area_fill is used for a line chart, then the default is 0. When set to a variable, activates a bubble plot, with the size of each bubble further determined by the value of radius. Applies to the standard two-variable scatterplot.

pt_size_cut

For a bubble plot in which bubble sizes are defined by a pt_size variable, controls whether and how many bubble labels are shown. If 1 (or TRUE), show the value of the sizing variable for selected bubbles in the center of the bubbles, except when the bubble is too small. If 0 (or FALSE), no values are displayed. If a number greater than 1, display labels only for the indicated number of values (e.g., the maximum and minimum when set to 2). The color of the displayed text is set by bubble_text from the style function.

pt_shape

Plot character(s). The default value is "circle", with both a default exterior color and filled interior, explicitly specified by "color" and "fill". Other possible values with fillable interiors are "circle", "square", "diamond", "triup" (triangle up), and "tridown" (triangle down), all uppercase and lowercase letters, all digits, and most punctuation characters. The integers 0–25 as defined by the base R points function also apply.

line_width

Width of the line segments that connect adjacent points, such as in time series plots. Set to 0 to remove line segments.

segments

Designed for interaction plots of means: connects each pair of successive points with a line segment. Pass a data frame of means, such as from pivot. To turn off connecting line segments for sorted, equal-interval data, set to FALSE. Currently, does not apply to Trellis plots.

sort

Sort the values of y by the values of x. Default "0" retains the original order, "-" sorts descending, and "+" sorts ascending. If x is a vector of two variables, sort by their difference.

jitter_x

Randomly perturb the plotted points of a scatterplot horizontally within the limits of the specified value, or set to NULL to rely upon the computed default value.

jitter_y

Vertical jitter. Defaults to 0. Same interpretation as jitter_x.


ID

Name of a variable that provides the labels for selected plotted points for outlier identification, row names of the data frame by default. To label all points, use the add parameter (see below).

ID_size

Size of the plotted labels. Modify label text color with the style function parameter ID_color.

MD_cut

Squared Mahalanobis distance cutoff to define an outlier in a two-variable scatterplot. The reported MD value is the squared distance, D^2, as returned by the Base R function mahalanobis. For bivariate data D^2 follows a chi-square distribution with 2 degrees of freedom, so the default cutoff of 6 is just beyond \chi^2_{.95}(2) = 5.99, the 0.95 data ellipse.

out_cut

Count or proportion of plotted points to label, in order of their distance from the center (means) of the univariate distribution or scatterplot, sorted from most to least extreme. For two-variable plots, distance from the center is based on the squared Mahalanobis distance.

out_shape

Shape of outlier points in a two-variable scatterplot. Modify fill color from the current theme with out_fill and out2_fill in style.

out_size

Size of outlier points in a two-variable scatterplot.


fit

Type of best fit line. Default is "off". Options include "loess" for a non-linear smooth, "lm" for a linear least squares model (with synonym "ls"), "null" for the null (intercept-only) model, "exp" for exponential growth or decay, "log" for a logarithmic model, "power" for a general power model in conjunction with fit_power, and "quad" for a quadratic (power 2) model. If potential outliers are identified according to out_cut, a second (dashed) fit line is displayed based on the data excluding those outliers.

fit_power

Power that describes the response y as a power function of the predictor x, required when fit="power". Optionally, and experimentally, may apply to fit="exp".

fit_se

Confidence level for the error band displayed around the line of best fit. Default is 0.95 when a fit line is specified, but is turned off when fit_errors=TRUE. Can be a vector to display multiple confidence bands. Set to 0 to suppress error bands. The band uses the residual degrees of freedom of the fit, n - 2 for a linear fit. A panel with too few points for a band, such as a facet, draws none.

fit_span_loess

Smoothing parameter for fit="loess", passed to loess. Larger values give a smoother curve. Default is 0.75.

fit_degree_loess

Degree of the polynomials fit locally by fit="loess", passed to loess, either 2, the default, or 1. Degree 1 fits lines and so smooths more, degree 2 fits parabolas and so follows a peak or a valley more closely.

fit_color

Color of the fit line.

fit_lwd

Line width of the fit line.

fit_new

When fit is set to a fitted curve such as "lm" or "quad", predicted values are computed at the x-values supplied here.

fit_errors

If TRUE, plot line segments joining each point to the regression line ("loess" or "lm"), illustrating the size of the residuals. Renamed from plot_errors.

ellipse

Confidence level of a data ellipse for a scatterplot of one x-variable and one y-variable according to the contours of the corresponding bivariate normal density. Specify the confidence level(s) as a single number or a vector of values between 0 and 1 to plot one or more ellipses. Ellipses are not available in the interactive plotly version. For Trellis graphics, only the maximum level is used, with one ellipse per panel. Modify fill and border colors with the style parameters ellipse_fill and ellipse_color.

ellipse_fill

Fill color of the ellipse.

ellipse_color

Edge color of ellipse.

ellipse_lwd

Line width of the ellipse.


ts_unit

Time unit for plotting time series data when x is of type Date. Default is to infer the unit from the observed date spacing. Specify ts_unit to override the inferred unit and, when requested, aggregate to a coarser unit. Valid values are "days", "weeks", "months", "quarters", "years", and "days7" (daily data with a 7-day seasonal cycle).

ts_ahead

Number of ts_unit steps ahead of the last time period to forecast.

ts_method

Forecasting method. Default is "es" for exponential smoothing models. Alternatively, choose "lm" for a least squares linear regression model that accounts for seasonality.

ts_source

Source of forecasting functions. Default is "fable" for access to ETS() and TSLM() from the fable package and related functions from the fpp3 ecosystem, or "classic" for base R forecasting functions.

ts_agg

Function used to aggregate over time according to ts_unit. Default is "sum" with an option for "mean".

ts_NA

By default, missing y values (NA) are not plotted, leaving gaps. Alternatively, specify a value, usually 0, to replace NA and plot that value (e.g., 0) at the corresponding date. Forecasting with missing data is not supported.

ts_format

Optional format string for as.Date() describing the values of the date variable on the x-axis, needed if the function cannot infer the date format. For example, the character string "09/01/2024" can be described by "%m/%d/%Y". See details for more information.

ts_fitted

If TRUE and ts_ahead is used for forecasting, display for each data point the fitted value, level, trend, and seasonal component.

ts_PI

Prediction interval level about the forecasted values, with default of 0.95.

ts_trend

Trend parameter. Default value is NULL, allowing the procedure to choose the specification that yields the best-fitting model for the data. Values "A" and "M" indicate additive and multiplicative models, respectively. Specify "N" to omit the trend component. See the forecasting documentation for valid combinations of trend, season, and error.

ts_seasons

Seasonality parameter. See ts_trend.

ts_error

Error parameter. See ts_trend.

ts_alpha

Exponential smoothing level parameter. Sets the value for HoltWinters(), and acts as a suggestion for ETS() in the "fable" framework.

ts_beta

Exponential smoothing trend parameter. See ts_alpha.

ts_gamma

Exponential smoothing seasonal parameter. See ts_alpha.

ts_new_x

A data frame of predictor variable names and new values for predictor variables used for model fitting and forecasting. The number of rows of new data values determines the number of future time periods for which forecasts are generated. Currently applies only to the default "fable" linear model for ts_method="lm".

ts_stack

If TRUE, multiple time plots are stacked on each other, with area set to TRUE by default.

ts_area_fill

Fill under line segments, if present. If ts_stack is TRUE, the default is a gradient from the default color range (e.g., "blues"). If not specified, and fill is set with no plotted points and ts_area_fill is not specified, then fill generally controls the area under the line segments.

ts_area_split

Applies only to a Trellis plot activated with facet. Value of y that defines a reference line splitting the filled area under the time series line. Values of y below this threshold lie below the reference line; values above lie above the line.

ts_n_x_tics

Suggested number of ticks for dates on the x-axis, overriding the default of approximately seven ticks.

show_runs

If TRUE, display the individual runs in the run analysis. Also sets run to TRUE. Customize the color of the line segments with segments_color via style.

center_line

Plots a dashed line through the middle of a run chart. Values are "off", "mean", "median", and "zero", which specify that the center line goes through the mean, median, or zero, respectively. When not specified, a "median" center line is displayed if the values frequently vary about the mean, otherwise no center line. Currently not supported for Trellis plots.


radius

Scaling factor of the bubbles in a bubble plot, which sets the radius of the largest displayed bubble in inches. To activate bubble scaling, set pt_size to a third variable, or for categorical variables (factors), the bubble sizes represent frequencies.

power

Relative scaling of bubble sizes. The default value of 0.5 scales bubbles so that the area of each bubble is proportional to the corresponding sizing variable. A value of 1 scales bubble radii directly by the sizing variable, increasing the size differences between values.

low_fill

For a categorical variable and the resulting bubble plot, or a matrix of such plots, sets the low end of a color gradient for bubble fill.

hi_fill

For a categorical variable and the resulting bubble plot, or a matrix of such plots, sets the high end of a color gradient for bubble fill.


smooth_points

Number of points superimposed on the density plot in the areas of lowest density to help identify outliers, thereby controlling how dark the smoothed display becomes.

smooth_size

Size of points superimposed on the density plot. Default value is 1, resulting in very small points.

smooth_power

Exponent of the function that maps the density scale to the color scale. Smaller values than the default of 0.25 yield darker plots.

smooth_bins

Number of bins in each direction for the density estimation.

hex_bins

Number of bins in each direction for the hexbin plot.

hexbin_legend

If TRUE, the default, display the color key (legend) that maps fill colors to the binned counts on the right side of the hexbin plot. Set to FALSE to suppress the legend.

n_bins

Number of bins for a single numeric x-variable when visualizing the mean or median of a numeric y-variable for each bin. Points are plotted as bubbles, with bubble size proportional to the bin sample size, unless pt_size is specified as a constant. Default is 1 (no binning).

contour_n

Number of contour levels in a contour plot, with default of 20.

contour_nbins

Number of bins constructed for each of x and y, forming the 2D grid from which densities are estimated.

contour_points

If TRUE, plot the original scatterplot points in a light gray with white borders, representing the data from which the contour curves are estimated. Color is not affected by other color settings, but point size can be changed with pt_size. Default size is 0.72.

contour_legend

If TRUE, display the color key (legend) that maps fill colors to density values on the right side of the contour plot. Default is FALSE (legend suppressed).


bin

If values="count", display the frequency distribution for a frequency polygon.

bin_start

Optional starting value of the bins for a frequency polygon.

bin_width

Optional specified bin width. Also sets bin=TRUE.

bin_end

Optional value that lies within the last bin, so the actual endpoint of the last bin may be larger than the specified value.

breaks

Method for calculating bins, or an explicit specification of the bins, such as via seq or other options provided by hist. Also sets bin=TRUE.

cumulate

If TRUE, display a cumulative frequency polygon.


xlab, ylab

Axis labels for the x- and y-axes. If not specified, labels default to the corresponding variable labels (if present), otherwise to the variable names. If xy_ticks is FALSE, no ylab is displayed. Customize these and related parameters with options such as lab_color in style.

main

Label for the plot title. If corresponding variable labels exist, the title is set by default from those labels.

sub

Subtitle for the graph, below xlab. Not yet implemented.

label_adjust

Two-element vector (x-axis label, y-axis label) that adjusts the positions of axis labels in approximate inches. Positive values move labels away from the plot edge. Not applicable to Trellis graphics.

margin_adjust

Four-element vector (top, right, bottom, left) that adjusts plot margins in approximate inches. Positive values move the corresponding margin away from the plot edge. Can be used with offset to move axis values into the expanded margin space. Not applicable to Trellis graphics.

pad_x

Proportion of padding added to the left and right sides of the x-axis. Values range from 0 to 1 for each of the two elements. If only one element is specified, it is applied to both sides.

pad_y

Proportion of padding added to the bottom and top sides of the y-axis. Values range from 0 to 1 for each of the two elements. If only one element is specified, it is applied to both sides.


scale_x

If specified, a vector of three values that define the numeric x-axis: starting value, ending value, and number of intervals.

scale_y

If specified, a vector of three values that define the numeric y-axis: starting value, ending value, and number of intervals.

origin_x

Origin of the x-axis. Default is the minimum value of x, except for time series plots and when stat is set to "count" or a related option, in which case the origin defaults to 0.

origin_y

Origin of the y-axis. Default is the minimum value of y, except for time series plots and when stat is set to "count" or a related option, in which case the origin defaults to 0.


rotate_x

Rotation in degrees of the axis value labels on the x-axis, usually to accommodate longer labels, typically used with offset. If set to 90, labels are perpendicular to the axis and a different placement algorithm is used so that offset is not needed.

rotate_y

Rotation in degrees of the axis value labels on the y-axis, usually to accommodate longer labels, typically used with offset.

offset

Spacing between axis value labels and the axis. Default is 0.5. Larger values (e.g., 1.0) create additional space for labels, especially when rotated. Can be used with margin_adjust to create additional margin space for axis labels and values.


axis_fmt

Numeric format of axis labels for both axes. Default rounds thousands to "K" (e.g., 100000 becomes 100K). Alternatives include "," to insert commas in large numbers with a decimal point, "." to insert periods, or "" to turn off formatting.

axis_x_prefix

Prefix for axis labels on the x-axis, such as "$".

axis_y_prefix

Prefix for axis labels on the y-axis, such as "$".

font_size

Multiplicative scaling factor applied to the font sizes of the title (main_size), axis labels (lab_size), and axis value text (axis_size) simultaneously, preserving their relative proportions. Default is 1 (no scaling).

xy_ticks

Flag indicating whether tick marks and associated value labels on the axes are displayed. To rotate axis values, use rotate_x, rotate_y, and offset (see style).

n_axis_x_skip

Particularly useful for Trellis or facet plots with many labels on the x-axis. Specifies the spacing for skipping labels. A value of 0 includes all labels (default). A value of 1 skips every other label, 2 includes every third label, etc. Also consider rotate_x.

n_axis_y_skip

Same as n_axis_x_skip but applies to the y-axis.


legend_title

Title of the legend for a multiple-variable x or y plot.


add

Overlay one or more objects, text or geometric figures, on the plot. Possible values include any text (first argument) or "text"; "labels" to label each point with the row name; and geometric objects "rect" (rectangle), "line", "arrow", "v_line" (vertical line), and "h_line" (horizontal line). The value "means" draws vertical and horizontal lines at the respective means. Does not apply to Trellis graphics. Customize with parameters such as add_fill and add_color via style.

x1

First x-coordinate for each overlaid object; may be "mean_x". Not used for "h_line".

y1

First y-coordinate for each overlaid object; may be "mean_y". Not used for "v_line".

x2

Second x-coordinate for each object; may be "mean_x". Used only for "rect", "line", and "arrow".

y2

Second y-coordinate for each object; may be "mean_y". Used only for "rect", "line", and "arrow".


quiet

If TRUE, suppress text output. Can change the system default with style.

do_plot

If TRUE (default), generate the plot.

use_plotly

If TRUE (default), draw a plotly interactive plot in the RStudio Viewer window in addition to the static plot in the Plots window. Not all options are available in the interactive version, but key options are supported.

pdf_file

If specified, direct PDF graphics to the given file name.

width

Width of the plot window in inches, default 5 except within RStudio, where the default maintains an approximately square plotting area.

height

Height of the plot window in inches, default 4.5 except for 1-D scatterplots and when running in RStudio.

digits_d

Number of significant digits for each displayed summary statistic.


eval_df

If TRUE, checks that variables exist in the supplied data frame. Default of NULL determines the setting automatically. Set to FALSE in Shiny or pipe workflows.

fun_call

Function call. Used with knitr to pass the function call when obtained from the abbreviated helper sp.


smooth

Deprecated. Now use parameter form.

stat

Deprecated. Functionality moved to Chart(). Apply a specified aggregation such as "mean" to the numerical y variable at each level of a categorical x variable. The resulting dot plot (Cleveland plot) is analogous to a bar chart but emphasizes position along a common scale.

stat_x

Deprecated. If no y variable is specified, constructs a frequency polygon for x with access to bin_width. Either use the default "count" for each bin or "proportion", also indicated by %.


type

Deprecated, renamed form. Retained as a parameter only so that a call that uses the former name is answered with the current name instead of a generic unused-argument message.

size

Deprecated, renamed pt_size. Retained for the same reason as type.

shape

Deprecated, renamed pt_shape. Retained for the same reason as type.

plot_errors

Deprecated, renamed fit_errors. Retained for the same reason as type.

span

Deprecated, renamed fit_span_loess. Retained for the same reason as type.

segments_x, segments_y

No longer parameters of XY(). Retained to report that a segment from each point to an axis belongs to the dot plot of a categorical variable, Chart with form="dot".

Details

PARAMETERS

XY() accepts only the parameters listed above, so that a misspelled name is reported by R at the call rather than passed silently to the underlying graphics. Appearance is set with style, before the call and for all subsequent visualizations, including the color and size of the title with main_color and main_size, of the subtitle with sub_color and sub_size, and the font family of all plotted text with font_family.

VARIABLES and TRELLIS PLOTS

There is at least one primary variable, x, which defines the horizontal x-axis. A second primary variable, y, defines the vertical y-axis. Either x or y (but not both simultaneously) may be a vector of variables. The simplest usage—single x and y—produces a single scatterplot on one panel. With form="scatter" this is a standard point plot; alternative values such as "smooth" and "contour" invoke 2-D kernel density and contour displays, respectively.

For numeric primary variables, multiple plots can appear on a single panel in two ways. First, by defining groups with the by argument: by identifies a categorical grouping variable, and a separate scatterplot layer is drawn for each of its levels. Group levels are distinguished by color and/or shape. By default, both colors and shapes vary across groups, which also aids readability for color-blind viewers; for two groups, a common pattern is a filled symbol for one group and a point with transparent interior for the other.

Second, multiple numeric x-variables or multiple y-variables can be supplied as a vector, which produces multiple series on the same panel. This is commonly used for time series overlays and multi-series line plots.

Trellis graphics (facets), from the Deepayan Sarkar (2009) package lattice, may also be used. A variable specified with facet is a conditioning variable. A single facet variable produces one panel for each of its levels; a length-two vector of facet variables produces one panel for each cross-classified combination of their levels. Within each panel, x and y are plotted as usual, and an additional grouping variable specified with by may be applied to all panels. When x has at most 1000 unique values, XY() can provide a brief diagnostic of the maximum number of repeated values for each level of facet.

A vector of variables passed to x (or y) combines with facet: the multi-series overlay is repeated across the panels, each panel displaying the full overlay for one level (or combination of levels) of the facet variable(s), with all panels on a common scale for direct comparison. Because the multiple series already occupy the color (series) dimension of the plot, by does not apply when x or y is a vector.

Control the panel dimensions and the overall size of the Trellis display with width and height for the graphics device, n_row and n_col for the number of panels in each direction, and aspect for the panel height-to-width ratio. The plot window is the active graphics device (e.g., the standard R plotting window, RStudio Plots pane, or a pdf file when pdf_file is specified).

CATEGORICAL VARIABLES

Categorical variables have relatively few unique values and are recommended to be often coded as factors. However, categorical variables may also be coded numerically, such as Likert responses from 1 to 5. The structuring arguments by and facet apply when at least one of x or y is numeric, but that numeric variable may represent either a truly continuous scale or a discrete Likert-type scale.

A continuous variable, including time, models an underlying continuous scale, even though all continuous variables are necessarily measured at discrete precision. The distinction from a categorical variable is the scale that the values represent, not the finiteness of the recorded values. A date-valued x is therefore a continuous variable, which is why the time-series display of XY() requires no qualification beyond continuous x.

Scatterplots of Likert-type data can be challenging because the number of possible joint values is small. For two five-point scales there are only 25 possible combinations, so many points overlap at the same coordinates. For such situations, jittering, or dot/mean plots (using stat) may provide clearer displays.

The relationship between two categorical variables is instead displayed with Chart, specifying form="bubble" and a by variable, which sizes each bubble by the joint frequency of the two categories.

DATA

The default input data frame is d. Another data frame can be specified with the data argument. Regardless of the name of the data frame, variables can be referenced directly by name—no need to attach the data frame or use d$name. Referenced variables may live in the data frame, the global environment, or both. If x is a time series of class ts, first extract the date and value components with tsExtract, then pass them to XY.

The plotted values can be the raw data themselves, or summaries derived from them. With a single numeric variable, counts or proportions can be plotted on the y-axis, optionally after binning x. For a categorical x-variable paired with a continuous y-variable, summary statistics such as means can be plotted at each level of x. When x is continuous and binning is desired, XY() uses the same binning parameters as X, such as bin_width, to override defaults. The stat parameter controls what is plotted (e.g., "data", "mean", "median"). By default, connecting line segments are drawn, yielding a frequency polygon. Turn off line segments by setting line_width=0.

The filter parameter subsets rows (cases) of the input data frame according to a logical expression or a vector of integers specifying row numbers to retain. Use standard R logical operators as described in Logic—for example, & (and), | (or), and ! (not)—and relational operators as described in Comparison such as == (equality), != (not equal), and > (greater than). To specify rows directly, create an integer vector using standard R syntax. See Examples.

VALUE LABELS
Deprecated. Use factor() instead.

The value_labels option can override the axis tick labels with user-supplied values. This is particularly useful for Likert-style data coded as integers: for example, a data value 0 can be displayed as "Strongly Disagree". These labels apply to integer categorical variables and to factor variables. Any spaces in a label are translated into line breaks to improve readability.

In current workflows, the recommended approach is to define factors with the desired labels directly, typically via factors, which allows convenient creation of labeled factors for one or more variables in a single statement.

VARIABLE LABELS

Base R does not natively support variable labels, but lessR stores labels in the data frame alongside the variables, typically created by Read or VariableLabels. When variable labels exist, XY() uses them by default for axis labels and in text output. Otherwise, the variable names are used.

TWO VARIABLE PLOT

With two variables specified, XY() behaves as follows. If the values of x are unsorted, have unequal intervals, or there is missing data in either variable, a standard scatterplot is produced (for form = "scatter"). When x is sorted with equal intervals and there are no missing values, the default display connects adjacent points with line segments, yielding a function or time-series style plot.

Supplying multiple continuous x-variables against a single y, or vice versa, produces multiple series on the same graph. The points for the second series reuse the first series' color but with transparent fill; for more series, additional colors from the current theme are used.

SCATTERPLOT MATRIX

If x and y specify the same vector of continuous variables, as in XY(c(Years, Pre, Post), c(Years, Pre, Post)), XY() generates a scatterplot matrix. To specify the variable list once, store it as a data frame subset and reference it for both x and y, as in vec <- d[, c("Years", "Pre", "Post")] followed by XY(vec, vec, data=NULL). The matrix adopts the current color theme. Individual colors (e.g., fill, color) can be overridden. The lower triangle shows the pairwise scatterplots, and the upper triangle shows the corresponding correlation coefficients.

The cells also render as densities, with form="contour" or form="smooth", which a matrix often needs because it is where overplotting is worst. Each cell holds a different pair of variables in their own units, so each gets its own kernel density and its own bands, with no scale pooled across cells. A cell defaults to 8 filled contour bands rather than the 20 of a single plot, too fine to resolve at cell size; set contour_n for more or fewer. A requested fit line is drawn over the density without its confidence band. form="hexbin" and form="sunflower" do not apply to a matrix. By default a non-linear loess fit line is added to each scatterplot; the fit parameter can be used to request a linear least squares line instead, along with fit_color to set its color.

SIZE VARIABLE
Specifying a numeric pt_size variable activates a bubble plot in which the area of each bubble is determined by the corresponding value of pt_size (modified by radius and power).

Shapes vary across groups by default. To set shapes explicitly, use pt_shape and provide a vector of values (e.g., created with c), one shape per level of the grouping variable in by, or set pt_shape to a single value (e.g., "circle") to use the same shape for all groups. To control colors, use fill with values for each by level.

Beyond the named shapes such as "circle", any single character (letters, digits, "+", "*", "#") may be used as a plotting symbol. Within a single specification, either use standard named shapes or single characters, but not both.

SCATTERPLOT ELLIPSE

For a scatterplot of two numeric variables, the ellipse argument requests one or more data ellipses, based on the contours of the corresponding bivariate normal density. For a single x- and y-variable pair, setting ellipse to a numeric value between 0 and 1 (e.g., 0.95) draws the corresponding probability contour. A vector of values produces multiple ellipses. XY() expands the axes as needed so that ellipses extending beyond the range of the data remain fully visible. For Trellis graphics, only the largest ellipse level is used (one ellipse per panel). Ellipse fill and border colors are controlled via ellipse_fill and ellipse_color in style.

TIME CHARTS

See https://web.pdx.edu/~gerbing/lessR/examples/Time.html for additional examples and explanation.

Run Chart

When x is the special variable .index, XY() produces a run chart of y. The keyword names no column of data, so it is matched without regard to case, as .index or .Index. The y-values are plotted against their index positions (1, 2, …), and run-chart diagnostics such as center lines and runs analysis can be displayed via the corresponding arguments.

Quantile-Quantile Chart

When x names a theoretical distribution, XY() produces the quantile-quantile chart of y against that distribution. As with .index, the keyword names no column of data, so it is matched without regard to case, as .normal or .NORMAL. Instead the x-values are generated, as the quantiles of the named distribution fit to y by the method of moments. Both axes accordingly carry the units of y, and the reference against which the data are read is the 45-degree line through the origin.

Four distributions are available, each fit in closed form, with no shape parameter left to estimate or to choose.

Keyword Fit from Requires
.normal mean and standard deviation of y
.lognormal mean and standard deviation of log(y) y > 0
.exponential mean of y y >= 0
.uniform mean and standard deviation of y

Because y accepts an expression, XY(.normal, log(Salary)) gives the same picture as XY(.lognormal, Salary). The difference is the scale of the axes: the lognormal keyword keeps them in the units of Salary itself.

Because the chart is an ordinary scatterplot, the compositions of XY() apply. A by variable overlays the groups and a facet variable panels them, in either case with the quantiles generated separately within each group from that group's own values, so the single 45-degree line serves every group. A group with fewer than three values does not define a distribution and so is not plotted.

With a by variable the x-axis is not a single distribution shared by the overlaid groups. Each group is read against its own fitted distribution, so a point's x-value is the value that group's own fit predicts at that quantile. Because those fits carry each group's mean and standard deviation, the groups separate along the reference line, which is what makes the one line correct for all of them: location and spread are read from position along the line, departure from the distribution from distance away from it. Overlaid groups can interleave, however, so facet reads more cleanly for more than two.

A faceted quantile-quantile chart squares its panels, with aspect defaulting to "iso" rather than to the usual "fill", because the shape of the plotted points is read against a line that should itself appear at 45 degrees. Its panel layout is left to lattice, which arranges the square panels to the shape of the graphics device, side by side in a wide window and stacked in a tall one. Set aspect, n_row or n_col to override either default, and n_axis_x_skip to thin the axis labels when many panels leave each one narrow.

Specify data=NULL to read y from the global environment, which also displays the distribution of a computed vector, such as the residuals from a fitted model.

Time Series Defined with Dates

If x is of type Date or an R time-series object, XY() produces a time series plot for each specified variable. Time-series data can be supplied in “long” format (a single column of values plus a date column) or in “wide” format (multiple time-series columns sharing a date index). XY() will attempt to convert character string date values (e.g., "08/18/1952") to Date via as.Date(), using default date formats when possible.

XY() makes a reasonable attempt to decode common date formats, but some formats (e.g., those with month names rather than numbers) may require an explicit format string via ts_format. If the default conversion fails or is ambiguous, specify the correct format using examples such as those in the table below. Note that ts_format can always be provided for explicit specification of the date format.

Example Date Format
--------------------------- -----------------
"2022-09-01" "%Y-%m-%d"
"2022/9/1" "%Y/%m/%d"
"2022.09.01" "%Y.%m.%d"
"09/01/2022" "%m/%d/%Y"
"9/1/22" "%m/%d/%y"
"September 1, 2022" "%B %d, %Y"
"Sep 1, 2022" "%b %d, %Y"
"20220901" "%Y%m%d"
--------------------------- -----------------

XY() also converts character-string dates such as "2024 Aug" and "2024 Q1", interpreting three-letter month abbreviations and quarter codes Q1–Q4.

Date order. Rows out of date order are sorted by date for the plot, within the levels of any by or facet variable, so the line does not connect the points back and forth in time. The data frame itself is unchanged, and a note gives the order_by() call that sorts it. Dates that repeat within a series, unless aggregated with ts_unit, indicate more than one series, and are reported with by, facet, or filter as the remedy.

Time unit and aggregation. The ts_unit argument controls the time unit used for plotting and, when specified, can also be used to aggregate the series to a coarser time unit. By default, XY() attempts to infer a regular time unit from the observed spacing of the dates (see ‘Detecting the Regularity of Dates’). You may specify ts_unit to override the inferred unit, including treating irregular dates as a regular unit for aggregation (for example, ts_unit="weeks"). The special value "days7" retains daily observations but evaluates seasonality on a 7-day cycle.

When aggregation is requested, the date index is aggregated with endpoints() and period.apply() from the xts package. The aggregation function is specified with ts_agg, default "sum", with "mean" as a common alternative.

Detecting the Regularity of Dates (ts_unit)

For time series operations, lessR attempts to infer the regularity of a date variable from the observed sequence of dates. The inferred unit is returned internally as tu_exist and is one of "days", "weeks", "years", "quarters", "months", or "unknown".

The decision rules are:

  1. Pre-processing. Dates are sorted and reduced to unique values. When a grouping variable is present, regularity is evaluated from the first level only (assuming dates are already time-sorted within that level). Day gaps are computed as positive differences between successive dates.

  2. Trivial / short series. If there are fewer than two dates, or if no positive gaps are available, the unit is set to "days".

  3. Fine units (gap-based). Let gap be the median of the positive day gaps (median is robust to occasional missing dates).

    • If gap == 1, then tu_exist="days".

    • If gap == 7, then the series is a candidate weekly series. The gap pattern is further examined to distinguish a regular weekly series (primarily 7-day gaps, with only occasional longer gaps) from an irregular reporting schedule (for example, many 14-day gaps). If judged sufficiently weekly, then tu_exist="weeks"; otherwise tu_exist="unknown".

  4. Coarse units (calendar-based). If the unit is still "unknown" after the fine-unit checks, the dates are examined for calendar structure. Let year, month, and day denote the corresponding calendar fields.

    • Years. If there is at most one observation per year and all observations share the same month and day-of-month (for example, January 1 each year), then tu_exist="years". Missing years are permitted.

    • Quarters. If there is at most one observation per calendar quarter (unique year–quarter combinations) and the median day gap between observations falls in the range 60–122 days, then the existing time unit is deemed as "quarters"

    . The reporting month and day-of-month may vary across quarters, and missing quarters are permitted. The gap range excludes sparse or irregular series that happen to have at most one observation per quarter by chance.

  5. Months. If the time variable is a Date but the observations occur exactly once per calendar month with no duplicates within a month and the sequence of months is regular (missing months become explicit NAs if present), then lessR treats the series as monthly and converts the index accordingly.

  6. Missing periods. When a regular unit is accepted ("weeks", "years", "quarters", or "months"), a flag has_missing_periods is set to TRUE if the sequence of inferred periods contains gaps (for example, a 14-day gap in an otherwise weekly series, or a missing month in an otherwise monthly series). If the series is classified as "unknown", has_missing_periods is not used.

If the user explicitly specifies ts_unit, that value is used for aggregation and modeling, overriding the inferred unit. In particular, a user-specified ts_unit="months" may treat one observation per month as monthly even if the reporting day varies across months, and a user-specified ts_unit="weeks" may treat dates as weekly even if the inferred regularity is "unknown".

Missing Data

For missing data, if a date is present but the corresponding y-value is NA, the line is broken at that point (no segment is drawn). If both the date and value are absent (the entire row is missing), the line connects the nearest observed dates, spanning the gap in calendar time but skipping the missing tick label. For example, if "2021-01-07" and "2021-01-09" are present but "2021-01-08" is absent, the plot includes points for the 7th and 9th connected by a line; the 8th does not appear on the axis.

Forecasting

Forecasting is activated by setting ts_ahead to a positive integer. The trend, seasonal, and error components for exponential smoothing and regression models follow the fable conventions and are controlled by ts_trend, ts_seasons, and ts_error. XY() supports four forecasting engines: ETS() and TSLM() from fable via ts_source="fable", and classic HoltWinters() and regression decomposition (stl() + lm()) via ts_source="classic". Multiplicative components require positive data. Additive trend is linear, while multiplicative trend corresponds to exponential growth or decay; additive and multiplicative seasonality scale the seasonal pattern differently as the series level changes.

Exponential smoothing via ETS() (the default when ts_source="fable") generally provides flexible model specification and often superior predictive performance compared to classic Holt–Winters. For regression with seasonality, TSLM() and the stl()+lm() approach both rely on least squares but handle seasonal structure differently. Setting ts_fitted=TRUE provides fitted values and decomposed trend and seasonal components for inspection.

2-D KERNEL DENSITY

Set form="smooth" to invoke smoothScatter and display a 2-D kernel density estimate for large data sets. The display respects the current theme. The smooth_points argument controls how many points from low-density regions are superimposed, smooth_bins sets the number of bins in each direction for density estimation, and smooth_power controls the transformation from density scale to color scale. Larger smooth_power values reduce saturation in low-density regions. These arguments map directly to nrpoints, nbin, and transformation in smoothScatter. Grid lines are disabled by default for smooth density plots, but can be re-enabled via the appropriate styling options (e.g., grid_color in style).

Alternatively, set form="contour" to plot contour lines of the estimated bivariate density, with the level resolution controlled by contour_n and contour_nbins.

Each of the "smooth", "contour", and "hexbin" forms also supports facet for coordinated small multiples, and every panel shares a common scale so the panels are directly comparable. Contour and smooth panels share a common kernel-density grid, bandwidth, and set of color levels; hexbin panels share a single count legend. Faceted contour and smooth plots are drawn as a base-R panel grid, whereas faceted hexbin plots use the native paneling of the hexbin package. So the density can be compared across panels, a faceted smooth plot estimates the density with kde2d rather than with smoothScatter, so its appearance differs slightly from the corresponding single, unfaceted plot.

COLORS

A global color theme for XY() and other lessR graphics can be set with style (e.g., style(theme="lightbronze")). The default theme is "lightbronze". A grayscale theme is available via "gray", and other themes (e.g., "sienna", "darkred") are described in style. The sub_theme="black" option yields a black background with partially transparent plotted colors.

Individual graphical elements (points, lines, panels, grid lines, etc.) can be customized with additional style arguments, such as panel_fill. For a subtle warm background, try panel_fill="snow"; very light grays such as "gray99" or "gray97" provide a neutral tone.

For many color options, the value "off" is equivalent to "transparent", removing the corresponding fill or border.

See showColors for a display of all named R colors and their RGB values.

ANNOTATIONS

The add argument and its related coordinates (x1, y1, x2, y2) annotate the plot with text and geometric objects. Each object type requires a specific set of coordinates, summarized below. x-coordinates may take the special value "mean_x" and y-coordinates may take "mean_y".

Value Object Required Coordinates
----------- ------------------- -----------------------
"text" text x1, y1
"point" point x1, y1
"rect" rectangle x1, y1, x2, y2
"line" line segment x1, y1, x2, y2
"arrow" arrow x1, y1, x2, y2
"v_line" vertical line x1
"h_line" horizontal line y1
"means" horizontal and vertical lines at the means
----------- ------------------- -----------------------

The value of add specifies the object type. For a single object, provide one value and its required coordinates. For multiple placements of the same object, supply coordinate vectors. For multiple different objects, supply a vector of add values and, for each coordinate argument (x1, y1, x2, y2), a vector whose elements correspond to the sequence of objects in add.

Styling options such as add_color, add_fill, and transparency may also be given as vectors, allowing different objects to have different colors or other properties.

PDF OUTPUT

To obtain pdf output, set pdf_file to a file name, optionally with width and height to control device size. The pdf is written to the current working directory, which can be explicitly set with setwd.

ADDITIONAL OPTIONS

Many commonly used graphical parameters from the base R function plot are passed through by XY(), including:

cex.main, col.lab, font.sub, etc.

Settings for main/sub-titles and axis annotation; see title and par.

main

Main title of the graph; see title.

xlim

Limits of the x-axis, expressed as c(x1, x2). Note that x1 > x2 is allowed and produces a reversed axis.

ylim

Limits of the y-axis.

VARIABLES AND EXPRESSIONS

A referenced variable in XY is by default a variable name (or vector of variable names), resolved from the referenced data frame (e.g., the default d) or, with data=NULL, from the user's workspace (global environment). A vector of variable names retains its column-selection meaning, as in the scatterplot matrix XY(c(Years, Pre, Post), c(Years, Pre, Post)).

The variable arguments x, y, by, and facet also accept expressions, evaluated first against the columns of the data frame, then against the user's workspace. The expression text serves as the variable label. For example:

    > XY(rnorm(50), rnorm(50))   # expressions, no data frame needed
    > XY(Years, log(Salary))     # Years, Salary resolved from d
    > XY(Years, Salary, by=cut(Pre, 2))  # expression as by variable

An expression that references a column of the data frame must evaluate to one value per row of the data frame.

For a scatterplot matrix, store the variable list once as a data frame subset and reference it for both x and y:

    > vec <- d[, c("Years", "Pre", "Post")]
    > XY(vec, vec, data=NULL)    # same matrix as the c() form above

Value

The output may be assigned to an R object; otherwise it is printed directly to the console. Each component appears only when the corresponding analytic option is activated. For example, outlier identification must be enabled (e.g., via MD_cut) for out_outliers to be included in the output.

To save the results, assign the output to an object, such as p <- XY(Years, Salary). Use names(p) to view the available components, and access any one by prefixing with p$, for example p$out_stats. Output can be viewed interactively at the console or inserted into R~Markdown documents for reproducible reporting.

READABLE OUTPUT

out_stats: Correlational analysis.
out_outliers: Squared Mahalanobis distance values for detected outliers.
out_frcst: Forecasted values.
out_fitted: Fitted values for the observed data.
out_coefs: Linear and seasonal coefficients from forecasting models.
out_smooth: Smoothing parameters from exponential smoothing models.
out_bubble: Bubble-plot settings, including radius and power.
out_reg: Regression statistics produced when fit is specified.

STATISTICS

outliers: Row numbers corresponding to detected outliers.

Author(s)

David W. Gerbing (Portland State University; gerbing@pdx.edu)

References

Murdoch, D, and Chow, E. D. (2013). ellipse function from the ellipse package.

Gerbing, D. W. (2023). R Data Analysis without Programming, 2nd edition, Chapter 10, NY: Routledge.

Gerbing, D. W. (2020). R Visualizations: Derive Meaning from Data, Chapter 5, NY: CRC Press.

Gerbing, D. W. (2021). Enhancement of the Command-Line Environment for use in the Introductory Statistics Course and Beyond, Journal of Statistics and Data Science Education, 29(3), 251-266, https://www.tandfonline.com/doi/abs/10.1080/26939169.2021.1999871.

Hyndman, R. J., & Athanasopoulos, G. (2021). Forecasting: Principles and Practice (3rd ed.). Melbourne, Australia: OTexts. Retrieved from https://otexts.com/fpp3/

Sarkar, Deepayan (2008) Lattice: Multivariate Data Visualization with R, Springer. http://lmdvr.r-forge.r-project.org/

Sievert, C. (2020). Interactive Web-Based Data Visualization with R, plotly, and shiny. Chapman and Hall/CRC. URL: https://plotly.com/r/

See Also

X, Chart, style, tsExtract.

Examples

# read the data
d <- rd("Employee", quiet=TRUE)
d <- d[.(random(0.6)),]  # less computationally intensive
dd=d

#---------------------------------------------------
# traditional scatterplot with two numeric variables
#---------------------------------------------------

# scatterplot with all defaults
XY(Years, Salary)
# or use Plot in place of XY, the older method

# an expression as a variable, evaluated against the data frame,
#   with the expression text as the variable label
XY(Years, log(Salary))

XY(Years, Salary, by=Gender, pt_size=2, fit="lm",
     fill=c(M="olivedrab3", W="gold1"),
     color=c(M="darkgreen", W="gold4"))

# maximum information, minimum input: scatterplot +
#  means, outliers, ellipse, least-squares lines with and w/o outliers
#  outliers labeled by the values of the variable Name
XY(Years, Salary, enhance=TRUE, ID=Name)

# extend x and y axes
XY(Years, Salary, scale_x=c(-10, 35, 10), scale_y=c(0,200000,10))

XY(Years, Salary, add="Hi", x1=c(12, 16, 18), y1=c(80000, 100000, 60000))

d <- factors(Gender, levels=c("M", "W"))
XY(Years, Salary, facet=Gender)
d <- dd



# just males employed more than 5 years
XY(Years, Salary, filter=(Gender=="M" & Years > 5))

# plot 0.95 data ellipse with the points identified that represent
#   outliers defined by a squared Mahalanobis distance larger than 6
# save outliers into R object out
d[1, "Salary"] <- 200000
out <- XY(Years, Salary, ellipse=0.95, MD_cut=6, ID=Name)

# new shape and point size, no grid or background color
# then put style back to default
style(panel_fill="powderblue", grid_color="powderblue")
XY(Years, Salary, pt_size=2, pt_shape="diamond")
style()

# translucent data ellipses without points or edges
#  show the idealized joint distribution for bivariate normality
style(ellipse_color="off")
XY(Years, Salary, pt_size=0, ellipse=seq(.1,.9,.10))
style()

# bubble plot with size determined by the value of Pre
# display the value for the bubbles with values of  min, median and max
XY(Years, Salary, pt_size=Pre, pt_size_cut=3)

# variables in a data frame not the default d
# plot 0.6 and 0.9 data ellipses with partially transparent points
# change color theme to gold with black background
style("gold", sub_theme="black")
XY(eruptions, waiting, transparency=.5, ellipse=seq(.6,.9), data=faithful)

# scatterplot with two x-variables, plotted against Salary
# define a new style, then back to default
style(window_fill=rgb(247,242,230, maxColorValue=255),
  panel_fill="off", panel_color="off", pt_fill="black", transparency=0,
  lab_color="black", axis_text_color="black",
  axis_y_color="off", grid_x_color="off", grid_y_color="black",
  grid_lty="dotted", grid_lwd=1)
XY(c(Pre, Post), Salary)
style()

# increase span (smoothing) of the loess fit
#   from the default of 0.75 to 1.25
# display confidence intervals about best-fit line at
#   0.95 confidence level
XY(Years, Salary, fit="loess", fit_span_loess=1.25)

# loess fit of lines instead of parabolas
XY(Years, Salary, fit="loess", fit_degree_loess=1)
   

# 2-D kernel density (more useful for larger sample sizes)
XY(Years, Salary, form="smooth")

# sunflower plot: one petal per observation at each coordinate
# petals require coincident values, so the form suits discrete or
#   rounded data, here the integer-valued Years and Pre
XY(Years, Pre, form="sunflower")


#------------------------------------------------------
# scatterplot matrix from a vector of numeric variables
#------------------------------------------------------

# with least squares fit line
XY(c(Salary, Years, Pre), c(Salary, Years, Pre), fit="lm")

# same matrix from a stored variable list, a data frame subset
vec <- d[, c("Salary", "Years", "Pre")]
XY(vec, vec, data=NULL)


#--------------------------------------------------------------
# Trellis graphics and by for groups with two numeric variables
#--------------------------------------------------------------

# Trellis plot with condition on 1-variable
# optionally re-order default alphabetical R ordering by converting
#   to a factor with lessR factors (which also does multiple variables)
# always save to the full data frame with factors
d <- factors(Gender, levels=c("M", "W"))
XY(Years, Salary, facet=Gender)
d <- Read("Employee", quiet=TRUE)



# all three by (categorical) variables
XY(Years, Salary, facet=c(Dept, Gender), by=Plan, n_axis_y_skip=1)

# vary both shape and color with a least-squares fit line for each group
style(color=c("darkgreen", "brown"))
XY(Years, Salary, facet=Gender, fit="lm", pt_shape=c("W","M"), pt_size=.8)
style("gray")

# compare the men and women Salary according to Years worked
#   with an ellipse for each group
XY(Years, Salary, by=Gender, ellipse=.50)



#--------------------------------------------------------------
# facet the bivariate density displays: contour, smooth, hexbin
#   each panel shares a common scale, so panels are comparable
#--------------------------------------------------------------


XY(Years, Salary, form="contour", facet=Gender)
XY(Years, Salary, form="smooth", facet=Gender)
XY(Years, Salary, form="hexbin", facet=Gender)

# suppress the shared count legend of the faceted hexbin
XY(Years, Salary, form="hexbin", facet=Gender, hexbin_legend=FALSE)



#--------------------------------------------------------------
# facet with a vector of x (or y) variables: the multi-series
#   overlay repeated across the panels of the facet variable
#--------------------------------------------------------------


# the Pre and Post overlay against Salary, one panel per Gender level
XY(c(Pre, Post), Salary, facet=Gender)

# the overlay on the y-axis instead: shared Years on the x-axis
XY(Years, c(Pre, Post), facet=Gender, fit="lm")




# quantile-quantile charts
#-------------------------
# normal q-q chart of Salary, with the 45-degree reference line
XY(.normal, Salary)

# against a right-skewed distribution instead
XY(.lognormal, Salary)

# a panel for each level of Gender, quantiles within each group
XY(.normal, Salary, facet=Gender)

# q-q chart of a computed vector, here the residuals of a fitted model
# m <- lm(Salary ~ Years, data=d)
# XY(.normal, residuals(m), data=NULL)


# time charts
#------------
# run chart, with default fill area
XY(.index, Salary, ts_area_fill="on")

# two run charts in same panel
# or could do a multivariate time series
XY(.index, c(Pre, Post))

# Trellis graphics run chart with custom line width, no points
XY(.index, Salary, facet=Gender, line_width=3, pt_size=0)

# daily time series plot
# create the daily time series from R built-in data set airquality
#oz.ts <- ts(airquality$Ozone, start=c(1973, 121), frequency=365)
#XY(oz.ts, data=NULL)

# multiple time series plotted from dates and stacked
# black background with translucent areas, then reset theme to default
style(sub_theme="black", color="steelblue2", transparency=.55,
  window_fill="gray10", grid_color="gray25")
date <- seq(as.Date("2013/1/1"), as.Date("2016/1/1"), by="quarter")
x1 <- rnorm(13, 100, 15)
x2 <- rnorm(13, 100, 15)
x3 <- rnorm(13, 100, 15)
df <- data.frame(date, x1, x2, x3)
rm(date); rm(x1); rm(x2); rm(x3)
XY(date, x1:x3, data=df)
style()

# aggregate monthly data to plot by quarter
n.q <- 42
month <- seq(as.Date("2013/1/1"), length=n.q, by="months")
x <- rnorm(n.q, 100, 15)
XY(month, x, ts_unit="quarters", data=NULL)


# trigger a time series with a Date variable specified first
# stock prices for three companies by month:  Apple, IBM, Intel
d <- rd("StockPrice")
# only plot Apple
XY(Month, Price, filter=(Company=="Apple"))
# Trellis plots, one for each company
XY(Month, Price, facet=Company, n_col=1)
# all three plots on the same panel, three shades of blue
XY(Month, Price, by=Company, color="blues")
# exponential smoothing forecast for next 12 months, 
#   aggregate monthly data by mean over quarters
XY(Month, Price, ts_ahead=12, ts_unit="quarters")




#------------
# annotations
#------------

d <- Read("Employee")

# add text at the one location specified by x1 and x2
XY(Years, Salary, add="Hi There", x1=12, y1=80000)
# add text at three different specified locations
XY(Years, Salary, add="Hi", x1=c(12, 16, 18), y1=c(80000, 100000, 60000))

# add three different text blocks at three different specified locations
XY(Years, Salary, add=c("Hi", "Bye", "Wow"), x1=c(12, 16, 18),
  y1=c(80000, 100000, 60000))

# add an 0.95 data ellipse and horizontal and vertical lines through the
#  respective means
XY(Years, Salary, ellipse=0.95, add=c("v_line", "h_line"),
  x1="mean_x", y1="mean_y")
# can be done also with the following short-hand
XY(Years, Salary, ellipse=0.95, add="means")

# a rectangle requires two points, four coordinates, <x1,y1> and <x2,y2>
style(add_trans=.8, add_fill="gold", add_color="gold4", add_lwd=0.5)
XY(Years, Salary, add="rect", x1=12, y1=80000, x2=16, y2=115000)

# the first object, a rectangle, requires all four coordinates
# the vertical line at x=2 requires only an x1 coordinate, listed 2nd
XY(Years, Salary, add=c("rect", "v_line"), x1=c(10, 2),
  y1=80000, x2=12, y2=115000)

# two different rectangles with different locations, fill colors and translucence
style(add_fill=c("gold3", "green"), add_trans=c(.8,.4))
XY(Years, Salary, add=c("rect", "rect"),
  x1=c(10, 2), y1=c(60000, 45000), x2=c(12, 75000), y2=c(80000, 55000))






#---------------
# function curve
#---------------

x <- seq(10,50,by=2)
y1 <- sqrt(x)
y2 <- x**.33
# x is sorted with equal intervals so run chart by default
XY(x, y1, data=NULL)

# multiple plots from variable vectors need to have the variables
#  in a data frame
d <- data.frame(x, y1, y2)
# if variables are in the user workspace and in a data frame
#   with the same names, the user workspace versions are used,
#   which do not work with vectors of variables, so remove
rm(x); rm(y1); rm(y2)
XY(x, c(y1, y2))


lessR documentation built on Nov. 4, 2026, 1:07 a.m.