Core implementation for dot plots and lollipop plots. This is the internal
workhorse dispatched by both DotPlot() and LollipopPlot(). It
renders a matrix of points where dot size encodes one variable and dot fill
colour encodes another, with optional background stripes and a lollipop
(bar + dot) display mode.
Usage
DotPlotAtomic(
data,
x,
y,
x_sep = "_",
y_sep = "_",
flip = FALSE,
lollipop = FALSE,
size_by = NULL,
fill_by = NULL,
fill_cutoff = NULL,
palreverse = FALSE,
size_name = NULL,
fill_name = NULL,
fill_cutoff_name = NULL,
size_min = 1,
size_max = 10,
theme = "theme_this",
theme_args = list(),
palette = "Spectral",
palcolor = NULL,
alpha = 1,
border_color = "black",
border_size = 0.5,
border_alpha = 1,
lower_quantile = 0,
upper_quantile = 0.99,
lower_cutoff = NULL,
upper_cutoff = NULL,
facet_by = NULL,
facet_scales = "fixed",
facet_ncol = NULL,
facet_nrow = NULL,
facet_byrow = TRUE,
x_text_angle = 0,
aspect.ratio = 1,
legend.position = "right",
legend.direction = "vertical",
add_bg = FALSE,
bg_palette = "stripe",
bg_palcolor = NULL,
bg_alpha = 0.2,
bg_direction = c("vertical", "horizontal", "v", "h"),
title = NULL,
subtitle = NULL,
xlab = NULL,
ylab = NULL,
keep_na = FALSE,
keep_empty = FALSE,
...
)Arguments
- data
A data frame.
- x
A character vector specifying the column(s) to use for the x-axis. Can be numeric (for scatter/lollipop mode) or factor/character (for dot matrix mode). When multiple columns are provided for a non-numeric axis, they are concatenated with
x_sepas the separator.- y
A character vector specifying the column(s) to use for the y-axis. Can be numeric (for scatter mode) or factor/character (for dot matrix or lollipop mode). When multiple columns are provided for a non-numeric axis, they are concatenated with
y_sepas the separator.- x_sep
A character string used to join multiple
xcolumn values into a single factor level. Only used when x is non-numeric and multiple columns are provided. Default:"_".- y_sep
A character string used to join multiple
ycolumn values into a single factor level. Only used when y is non-numeric and multiple columns are provided. Default:"_".- flip
A logical value. If
TRUE, the x and y axes are swapped viacoord_flip(). Dimension calculation accounts for the flip. Default:FALSE.- lollipop
A logical value. If
TRUE, renders a lollipop plot with bars extending from x = 0 to each data point, capped by filled dots. Requiresxto be numeric andyto be factor/character. Default:FALSE.- size_by
A character string naming a numeric column whose values control dot size. When
NULL(the default), the per-combination observation count is computed automatically (viadplyr::summarise(n = n())) and used as the size variable. Iffill_byis also present, the first value offill_byper combination is retained with a warning. A single numeric value is also accepted and sets a constant dot size (used byScatterPlot).- fill_by
A character string naming a numeric column whose values control the fill colour of the dots (and lollipop inner bars). A continuous gradient from
paletteis applied viascale_fill_gradientn(). WhenNULL(the default), all dots are filled with a single constant colour from the middle of the palette.- fill_cutoff
A string expression specifying which values of
fill_byto grey out. Format: an operator followed by a number, e.g."< 18","<= 18","> 18", or">= 18". Values matching the condition are set toNAand rendered in grey ("grey80"), while the rest are coloured by the fill gradient. The operator determines which side of the threshold is greyed out, independent ofpalreverse. A numeric value is also accepted as shorthand for"<"(e.g.18is equivalent to"< 18"). Requiresfill_byto be set.- palreverse
A logical value indicating whether to reverse the palette. Default is FALSE.
- size_name
A character string for the size legend title. When
NULL(the default), thesize_bycolumn name is used.- fill_name
A character string for the fill colour-bar legend title. When
NULL(the default), thefill_bycolumn name is used.- fill_cutoff_name
A character string for the fill cutoff legend title (shown when
fill_cutoffis active). Defaults to"<fill_by> <fill_cutoff>", e.g."mpg < 18".- size_min
A numeric value for the smallest dot size in the
scale_size(range = c(size_min, size_max))range. Default:1.- size_max
A numeric value for the largest dot size in the
scale_size(range = c(size_min, size_max))range. Default:10.- theme
A character string or a theme class (i.e. ggplot2::theme_classic) specifying the theme to use. Default is "theme_this".
- theme_args
A list of arguments to pass to the theme function.
- palette
A character string specifying the palette to use. A named list or vector can be used to specify the palettes for different
split_byvalues.- palcolor
A character string specifying the color to use in the palette. A named list can be used to specify the colors for different
split_byvalues. If some values are missing, the values from the palette will be used (palcolor will be NULL for those values).- alpha
A numeric value specifying the transparency of the plot.
- border_color
Controls the dot border colour and lollipop outer-shadow appearance:
TRUE— dot borders and lollipop inner bars follow thefill_bygradient viascale_color_gradientn(); lollipop outer shadow is black."black"(default) — constant black borders on dots and black outer shadow on lollipop bars.A colour string (e.g.
"red","#FF0000") — constant colour for both dot borders and lollipop outer shadows.FALSE— no dot borders and no lollipop outer shadow (the inner coloured bars remain visible in lollipop mode).
- border_size
A numeric value for the stroke width of dot borders and the base linewidth of lollipop bars. In lollipop mode, the outer shadow uses
border_size * 4and the inner bar usesborder_size * 2. Default:0.5.- border_alpha
A numeric value in
[0, 1]controlling the transparency of dot borders and lollipop bar segments. Default:1.- lower_quantile, upper_quantile
Lower and upper quantiles for the continuous color/fill scale. The actual cutoffs are determined by these quantiles when
lower_cutoffandupper_cutoffareNULL. Defaults:lower_quantile = 0,upper_quantile = 0.99.- lower_cutoff, upper_cutoff
Explicit lower and upper cutoffs for the continuous color/fill scale. When
NULL(the default), the cutoffs are determined bylower_quantileandupper_quantileviaquantile. Values outside the[lower_cutoff, upper_cutoff]range are clamped (winsorized) to the nearest cutoff value.- facet_by
A character string specifying the column name of the data frame to facet the plot. Otherwise, the data will be split by
split_byand generate multiple plots and combine them into one usingpatchwork::wrap_plots- facet_scales
Whether to scale the axes of facets. Default is "fixed" Other options are "free", "free_x", "free_y". See
ggplot2::facet_wrap- facet_ncol
A numeric value specifying the number of columns in the facet. When facet_by is a single column and facet_wrap is used.
- facet_nrow
A numeric value specifying the number of rows in the facet. When facet_by is a single column and facet_wrap is used.
- facet_byrow
A logical value indicating whether to fill the plots by row. Default is TRUE.
- x_text_angle
A numeric value specifying the angle of the x-axis text.
- aspect.ratio
A numeric value specifying the aspect ratio of the plot.
- legend.position
A character string specifying the position of the legend. if
waiver(), for single groups, the legend will be "none", otherwise "right".- legend.direction
A character string specifying the direction of the legend.
- add_bg
A logical value. If
TRUE, alternating background stripes are drawn behind the points viabg_layer(). The striped axis is determined bybg_direction. Requires the striped axis to be non-numeric. Default:FALSE.- bg_palette
A character string specifying the palette for the background stripe colours. Passed to
bg_layer(). Default:"stripe".- bg_palcolor
A character vector of colours for the background stripes. Passed to
bg_layer(). WhenNULL(default), colours are derived frombg_palette.- bg_alpha
A numeric value in
[0, 1]for the transparency of the background stripes. Default:0.2.- bg_direction
A character string specifying which axis receives the alternating background stripes.
"vertical"(default) stripes by x levels;"horizontal"stripes by y levels. Abbreviations"v"and"h"are also accepted.- title
A character string specifying the title of the plot. A function can be used to generate the title based on the default title. This is useful when split_by is used and the title needs to be dynamic.
- subtitle
A character string specifying the subtitle of the plot.
- xlab
A character string specifying the x-axis label.
- ylab
A character string specifying the y-axis label.
- keep_na
A logical value or a character to replace the NA values in the data. It can also take a named list to specify different behavior for different columns. If TRUE or NA, NA values will be replaced with NA. If FALSE, NA values will be removed from the data before plotting. If a character string is provided, NA values will be replaced with the provided string. If a named vector/list is provided, the names should be the column names to apply the behavior to, and the values should be one of TRUE, FALSE, or a character string. Without a named vector/list, the behavior applies to categorical/character columns used on the plot, for example, the
x,group_by,fill_by, etc.- keep_empty
One of FALSE, TRUE and "level". It can also take a named list to specify different behavior for different columns. Without a named list, the behavior applies to the categorical/character columns used on the plot, for example, the
x,group_by,fill_by, etc.FALSE(default): Drop empty factor levels from the data before plotting.TRUE: Keep empty factor levels and show them as a separate category in the plot."level": Keep empty factor levels, but do not show them in the plot. But they will be assigned colors from the palette to maintain consistency across multiple plots. Alias:levels
- ...
Additional arguments.
Details
The function supports two display modes:
Dot plot (
lollipop = FALSE, the default) — rendersggplot2::geom_point()withshape = 21(filled circle). Either or both axes can be numeric (producing a scatter plot) or factor (producing a dot matrix). Dot size scales bysize_by(or the per-combination observation count whensize_byisNULL) viascale_size(range = c(size_min, size_max)). Dot fill follows thefill_bycolumn viascale_fill_gradientn().Lollipop plot (
lollipop = TRUE) — expects a numericxand a factor/charactery. Renders a two-layer bar: an outer shadow segment followed by an inner coloured segment, each capped by a filled dot. The outer shadow is black (or a custom colour whenborder_coloris a string), and the inner segment + dot fill followfill_by.
When add_bg = TRUE, alternating background stripes are drawn via
bg_layer() along the discrete axis (vertical stripes for
factor x, horizontal stripes for factor y). The fill colour
scale is prepared via prepare_continuous_color_scale() and
can be trimmed with lower_quantile/upper_quantile or
lower_cutoff/upper_cutoff.
When fill_cutoff is set (e.g. "< 18"), values of
fill_by matching the condition are set to NA and rendered in
grey ("grey80"), with a separate legend entry documenting the cutoff.
Border colour modes:
border_color = TRUE— dot borders and lollipop inner bar colour track thefill_bygradient viascale_color_gradientn(); lollipop outer shadow is black.border_color = "black"(default) — constant black borders on dots and a black outer shadow on lollipop bars.border_color = FALSE— no dot borders, no lollipop outer shadow (the inner coloured segment remains).
Architecture
DotPlotAtomic executes the following steps:
ggplot dispatch — selects
gglogger::ggplotorggplot2::ggplotbased ongetOption("plotthis.gglogger.enabled").bg_direction normalisation —
match.arg()resolves"v"/"h"abbreviations to"vertical"/"horizontal".Axis type detection — determines whether
x(resp.y) is numeric by checking that the column is a single name and the data column is neither character nor factor.Column resolution — non-numeric x and y are processed via
check_columns()withforce_factor = TRUE, allow_multi = TRUE, concat_multi = TRUEusingx_sep/y_sep.fill_byandfacet_byare also validated.NA / empty handling —
process_keep_na_empty()filters data and extractskeep_emptysettings for x, y, and facet_by.Multi-facet keep_empty guard — when
facet_byhas more than one column, thekeep_emptyvalues must be identical for all facet columns (consistent drop behaviour).fill_cutoff guard — errors if
fill_cutoffis set butfill_byisNULL.Size-by resolution — when
size_by = NULL:Groups data by the unique combination of x, y, and facet_by columns and counts rows per combination into
.size.If
fill_byis present,summarise()also takes the first value offill_byper group (with a warning that only the first value is used).Factor levels of x, y, and facet_by are preserved post-summary.
Sets
size_by <- ".size".
fill_cutoff parsing — if
fill_cutoffis set:Numeric shorthand (e.g.
18) is converted to"< 18".The string is parsed with regex
^(<=?|>=?)\\s*(-?[0-9.]+)$to extract operator and numeric threshold.A
switch()on the operator NAs-out matching values infill_by(e.g."<"sets values below the threshold toNA).A label
"<fill_by> <fill_cutoff>"is generated for the legend.
Default fill_by — when
fill_by = NULL, a synthetic.fill_bycolumn (constant1) is created and the fill legend is suppressed.Continuous colour scale preparation — when
fill_byis numeric,prepare_continuous_color_scale()computesfeat_colors_value(the range endpoints after optional quantile trimming or cutoff clamping).Base ggplot — initialises
ggplot(data, aes(x, y)).Background layer — if
add_bg = TRUE:Vertical stripes (
bg_direction = "vertical") require a non-numeric x-axis; horizontal stripes require a non-numeric y-axis.Calls
bg_layer()with the relevant discrete column and stripe styling.
Discrete axis scales —
scale_x_discrete()/scale_y_discrete()withdrop = !isTRUE(keep_empty_*)for non-numeric axes.Lollipop branch (
lollipop = TRUE):Sets x-axis expansion to
c(0, 0, 0.05, 0)(bars start at x = 0 with a 5\Outer shadow —
geom_segment()from x = 0 to the data value, coloured black (orborder_colorwhen a string), with linewidthborder_size * 4. Skipped whenborder_color = FALSE.Inner coloured bar —
geom_segment()mapped to thefill_bygradient viascale_color_gradientn(), with linewidthborder_size * 2.ggnewscale::new_scale_color()resets the colour scale for the subsequent point layer.
Point layer —
geom_point(shape = 21)(filled circle with border) with four dispatch paths:Numeric size + gradient border:
aes(fill, color)both mapped tofill_by;size = size_byconstant.Numeric size + constant/no border:
aes(fill, color = "")with a constant colour string.Column size + gradient border:
aes(size, fill, color)withscale_size(range = c(size_min, size_max))and a size legend (title =size_name, order = 1).Column size + constant/no border:
aes(size, fill, color = "")with the same size scale.
Fill scale —
scale_fill_gradientn()withpalette_this(),feat_colors_valuefor rescaled colour mapping,na.value = "grey80", and a colour-bar legend (title =fill_name, order = 2) orguide_none()when nofill_bywas provided.Labels —
labs(title, subtitle, x, y)with fallback to column names via%||%.Theme —
do_call(theme, theme_args)pluspanel.grid.major(grey80 dashed) and rotated x-axis text viacalc_just(x_text_angle).Colour (border) scale:
border_color = TRUE—scale_color_gradientn()following thefill_bygradient (with border_alpha), guide suppressed (the fill colour-bar serves both).border_color = FALSE—scale_color_manual()with"transparent", guide suppressed.Constant string —
scale_color_manual()with the alpha-adjusted colour, guide suppressed.
fill_cutoff legend — when
fill_cutoffis active and there are NA values infill_by, aguide_legend()(order = 3) is added showing the cutoff label with a grey fill and the border colour.Flip — optional
coord_flip()swaps x and y axes.Dimension calculation —
calculate_plot_dimensions()withbase_height = 4.5,aspect.ratio = NULL, and per-axis scale factors (0.9 for the categorical axis driving width, 0.6 for the categorical axis driving height). Legend width, y-axis label length, and minimum dimensions (width \(\ge\) 5, height \(\ge\) 4) are factored in. A fallback manual calculation is used whencalculate_plot_dimensions()returnsNULL.Faceting —
facet_plot()appliesfacet_grid/facet_wrapwithdrop = !isTRUE(keep_empty_facet).
