Skip to content

Violin quantiles are based on observations #5912

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Jan 27, 2025
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 126 additions & 3 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,132 @@
# ggplot2 (development version)

* (breaking) `geom_violin(draw_quantiles)` now has actual quantiles based on
* `guide_*()` can now accept two inside legend theme elements:
`legend.position.inside` and `legend.justification.inside`, allowing inside
legends to be placed at different positions. Only inside legends with the same
position and justification will be merged (@Yunuuuu, #6210).
* New stat: `stat_manual()` for arbitrary computations (@teunbrand, #3501)
* Reversal of a dimension, typically 'x' or 'y', is now controlled by the
`reverse` argument in `coord_cartesian()`, `coord_fixed()`, `coord_radial()`
and `coord_sf()`. In `coord_radial()`, this replaces the older `direction`
argument (#4021, @teunbrand).
* `coord_radial()` displays minor gridlines now (@teunbrand).
* (internal) `continuous_scale()` and `binned_scale()` sort the `limits`
argument internally (@teunbrand).
* Theme margins can have NA-units to inherit from parent elements. The new
function `margin_part()` has NA-units as default (@teunbrand, #6115)
* New `margin_auto()` specification for theme margins.
* New argument `labs(dictionary)` to label based on variable name rather than
based on aesthetic (@teunbrand, #5178)
* Fixed bug in out-of-bounds binned breaks (@teunbrand, #6054)
* Binned guides now accept expressions as labels (@teunbrand, #6005)
* (internal) `Scale$get_labels()` format expressions as lists.
* In non-orthogonal coordinate systems (`coord_sf()`, `coord_polar()` and
`coord_radial()`), using 'AsIs' variables escape transformation when
both `x` and `y` is an 'AsIs' variable (@teunbrand, #6205).
* The following methods have been deprecated: `fortify.lm()`, `fortify.glht()`,
`fortify.confint.glht()`, `fortify.summary.glht()` and `fortify.cld()`. It
is recommend to use `broom::augment()` and `broom::tidy()` instead
(@teunbrand, #3816).
* Custom and raster annotation now respond to scale transformations, and can
use AsIs variables for relative placement (@teunbrand based on
@yutannihilation's prior work, #3120)
* When discrete breaks have names, they'll be used as labels by default
(@teunbrand, #6147).
* The helper function `is.waiver()` is now exported to help extensions to work
with `waiver()` objects (@arcresu, #6173).
* Date(time) scales now throw appropriate errors when `date_breaks`,
`date_minor_breaks` or `date_labels` are not strings (@RodDalBen, #5880)
* `geom_errorbarh()` is deprecated in favour of
`geom_errorbar(orientation = "y")` (@teunbrand, #5961).
* `geom_contour()` should be able to recognise a rotated grid of points
(@teunbrand, #4320)
* `geom_boxplot()` gains additional arguments to style the colour, linetype and
linewidths of the box, whiskers, median line and staples (@teunbrand, #5126)
* `geom_violin()` gains additional arguments to style the colour, linetype and
linewidths of the quantiles, which replace the now-deprecated `draw_quantiles`
argument (#5912).
* (breaking) `geom_violin(quantiles)` now has actual quantiles based on
the data, rather than inferred quantiles based on the computed density. The
`draw_quantiles` parameter now belongs to `stat_ydensity()` instead of
`geom_violin()`. (@teunbrand, #4120)
`quantiles` parameter that replaces `draw_quantiles` now belongs to
`stat_ydensity()` instead of `geom_violin()` (@teunbrand, #4120).
* (internal) Using `after_scale()` in the `Geom*$default_aes()` field is now
evaluated in the context of data (@teunbrand, #6135)
* Fixed bug where binned scales wouldn't simultaneously accept transformations
and function-limits (@teunbrand, #6144).
* Fixed bug where the `ggplot2::`-prefix did not work with `stage()`
(@teunbrand, #6104).
* New `get_labs()` function for retrieving completed plot labels
(@teunbrand, #6008).
* Built-in `theme_*()` functions now have `ink` and `paper` arguments to control
foreground and background colours respectively (@teunbrand)
* The `summary()` method for ggplots is now more terse about facets
(@teunbrand, #5989).
* `guide_bins()`, `guide_colourbar()` and `guide_coloursteps()` gain an `angle`
argument to overrule theme settings, similar to `guide_axis(angle)`
(@teunbrand, #4594).
* `coord_*(expand)` can now take a logical vector to control expansion at any
side of the panel (top, right, bottom, left) (@teunbrand, #6020)
* (Breaking) The defaults for all geoms can be set at one in the theme.
(@teunbrand based on pioneering work by @dpseidel, #2239)
* A new `theme(geom)` argument is used to track these defaults.
* The `element_geom()` function can be used to populate that argument.
* The `from_theme()` function allows access to the theme default fields from
inside the `aes()` function.
* Passing empty unmapped aesthetics to layers raises a warning instead of
throwing an error (@teunbrand, #6009).
* Moved {mgcv} from Imports to Suggests (@teunbrand, #5986)
* New `reset_geom_defaults()` and `reset_stat_defaults()` to restore all geom or
stat default aesthetics at once (@teunbrand, #5975).
* `facet_wrap()` can have `space = "free_x"` with 1-row layouts and
`space = "free_y"` with 1-column layouts (@teunbrand)
* Secondary axes respect `n.breaks` setting in continuous scales (@teunbrand, #4483).
* Layers can have names (@teunbrand, #4066).
* (internal) improvements to `pal_qualitative()` (@teunbrand, #5013)
* `coord_radial(clip = "on")` clips to the panel area when the graphics device
supports clipping paths (@teunbrand, #5952).
* (internal) Panel clipping responsibility moved from Facet class to Coord
class through new `Coord$draw_panel()` method.
* `theme(strip.clip)` now defaults to `"on"` and is independent of Coord
clipping (@teunbrand, 5952).
* (internal) rearranged the code of `Facet$draw_panels()` method (@teunbrand).
* Axis labels are now justified across facet panels (@teunbrand, #5820)
* Fixed bug in `stat_function()` so x-axis title now produced automatically
when no data added. (@phispu, #5647).
* geom_sf now accepts shape names (@sierrajohnson, #5808)
* Added `gg` class to `labs()` (@phispu, #5553).
* Missing values from discrete palettes are no longer translated
(@teunbrand, #5929).
* Fixed bug in `facet_grid(margins = TRUE)` when using expresssions
(@teunbrand, #1864).
* `geom_step()` now supports the `orientation` argument (@teunbrand, #5936).
* `position_dodge()` and `position_jitterdodge()` now have a `reverse` argument
(@teunbrand, #3610)
* `coord_radial(r.axis.inside)` can now take a numeric value to control
placement of internally placed radius axes (@teunbrand, #5805).
* (internal) default labels are derived in `ggplot_build()` rather than
in `ggplot_add.Layer()` (@teunbrand, #5894)
* An attempt is made to use a variable's label attribute as default label
(@teunbrand, #4631)
* Themes gain an additional `header_family` argument to easily set the font
for headers and titles (#5886).
* The `plot.subtitle`, `plot.caption` and `plot.tag` theme elements now inherit
from the root `text` element instead of the `title` element (#5886).
* ggplot2 no longer imports {glue} (@teunbrand, #5986).
* `geom_rect()` can now derive the required corners positions from `x`/`width`
or `y`/`height` parameterisation (@teunbrand, #5861).
* All position scales now use the same definition of `x` and `y` aesthetics.
This lets uncommon aesthetics like `xintercept` expand scales as usual.
(#3342, #4966, @teunbrand)
* Bare numeric values provided to Date or Datetime scales get inversely
transformed (cast to Date/POSIXct) with a warning (@teunbrand).
* `stat_bin()` now accepts functions for argument `breaks` (@aijordan, #4561)
* (internal) The plot's layout now has a coord parameter that is used to
prevent setting up identical panel parameters (#5427)
* (internal) rearranged the code of `Facet$draw_panels()` method (@teunbrand).
* `geom_rug()` prints a warning when `na.rm = FALSE`, as per documentation (@pn317, #5905)
* `position_dodge(preserve = "single")` now handles multi-row geoms better,
such as `geom_violin()` (@teunbrand based on @clauswilke's work, #2801).
* `position_jitterdodge()` now dodges by `group` (@teunbrand, #3656)
* The `arrow.fill` parameter is now applied to more line-based functions:
`geom_path()`, `geom_line()`, `geom_step()` `geom_function()`, line
geometries in `geom_sf()` and `element_line()`.
Expand Down
74 changes: 59 additions & 15 deletions R/geom-violin.R
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@
#' finite, boundary effect of default density estimation will be corrected by
#' reflecting tails outside `bounds` around their closest edge. Data points
#' outside of bounds are removed with a warning.
#' @param quantile.colour,quantile.color,quantile.linewidth,quantile.linetype
#' Default aesthetics for the quantile lines. Set to `NULL` to inherit from
#' the data's aesthetics. By default, quantile lines are hidden and can be
#' turned on by changing `quantile.linetype`.
#' @param draw_quantiles `r lifecycle::badge("deprecated")` Previous
#' specification of drawing quantiles.
#' @export
#' @references Hintze, J. L., Nelson, R. D. (1998) Violin Plots: A Box
#' Plot-Density Trace Synergism. The American Statistician 52, 181-184.
Expand Down Expand Up @@ -91,11 +97,44 @@
...,
trim = TRUE,
bounds = c(-Inf, Inf),
quantile.colour = NULL,
quantile.color = NULL,
quantile.linetype = 0L,
quantile.linewidth = NULL,
draw_quantiles = deprecated(),
scale = "area",
na.rm = FALSE,
orientation = NA,
show.legend = NA,
inherit.aes = TRUE) {

extra <- list()
if (lifecycle::is_present(draw_quantiles)) {
deprecate_soft0(
"3.6.0",
what = "geom_violin(draw_quantiles)",
with = "geom_violin(quantiles.linetype)"
)
check_numeric(draw_quantiles)

Check warning on line 118 in R/geom-violin.R

View check run for this annotation

Codecov / codecov/patch

R/geom-violin.R#L113-L118

Added lines #L113 - L118 were not covered by tests

# Pass on to stat when stat accepts 'quantiles'
stat <- check_subclass(stat, "Stat", current_call(), caller_env())
if ("quantiles" %in% stat$parameters()) {
extra$quantiles <- draw_quantiles

Check warning on line 123 in R/geom-violin.R

View check run for this annotation

Codecov / codecov/patch

R/geom-violin.R#L121-L123

Added lines #L121 - L123 were not covered by tests
}

# Turn on quantile lines
if (!is.null(quantile.linetype)) {
quantile.linetype <- max(quantile.linetype, 1)

Check warning on line 128 in R/geom-violin.R

View check run for this annotation

Codecov / codecov/patch

R/geom-violin.R#L127-L128

Added lines #L127 - L128 were not covered by tests
}
}

quantile_gp <- list(
colour = quantile.color %||% quantile.colour,
linetype = quantile.linetype,
linewidth = quantile.linewidth
)

layer(
data = data,
mapping = mapping,
Expand All @@ -110,6 +149,8 @@
na.rm = na.rm,
orientation = orientation,
bounds = bounds,
quantile_gp = quantile_gp,
!!!extra,
...
)
)
Expand Down Expand Up @@ -140,7 +181,7 @@
flip_data(data, params$flipped_aes)
},

draw_group = function(self, data, ..., flipped_aes = FALSE) {
draw_group = function(self, data, ..., quantile_gp = list(linetype = 0), flipped_aes = FALSE) {
data <- flip_data(data, flipped_aes)
# Find the points for the line to go all the way around
data <- transform(data,
Expand All @@ -159,25 +200,28 @@
newdata <- vec_rbind0(newdata, newdata[1,])
newdata <- flip_data(newdata, flipped_aes)

# Draw quantiles if requested, so long as there is non-zero y range
if ("quantile" %in% names(newdata)) {
violin_grob <- GeomPolygon$draw_panel(newdata, ...)

quantiles <- newdata[!is.na(newdata$quantile),]
quantiles$group <- match(quantiles$quantile, unique(quantiles$quantile))
if (!"quantile" %in% names(newdata) ||
all(quantile_gp$linetype == 0) ||
all(quantile_gp$linetype == "blank")) {
return(ggname("geom_violin", violin_grob))
}

quantile_grob <- if (nrow(quantiles) == 0) {
zeroGrob()
} else {
GeomPath$draw_panel(quantiles, ...)
}
# Draw quantiles if requested, so long as there is non-zero y range
quantiles <- newdata[!is.na(newdata$quantile),]
quantiles$group <- match(quantiles$quantile, unique(quantiles$quantile))
quantiles$linetype <- quantile_gp$linetype %||% quantiles$linetype
quantiles$linewidth <- quantile_gp$linewidth %||% quantiles$linewidth
quantiles$colour <- quantile_gp$colour %||% quantiles$colour

ggname("geom_violin", grobTree(
GeomPolygon$draw_panel(newdata, ...),
quantile_grob)
)
quantile_grob <- if (nrow(quantiles) == 0) {
zeroGrob()
} else {
ggname("geom_violin", GeomPolygon$draw_panel(newdata, ...))
GeomPath$draw_panel(quantiles, ...)
}

ggname("geom_violin", grobTree(violin_grob, quantile_grob))
},

draw_key = draw_key_polygon,
Expand Down
26 changes: 13 additions & 13 deletions R/stat-ydensity.R
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#' @param drop Whether to discard groups with less than 2 observations
#' (`TRUE`, default) or keep such groups for position adjustment purposes
#' (`FALSE`).
#' @param draw_quantiles If not `NULL` (default), compute the `quantile` variable
#' @param quantiles If not `NULL` (default), compute the `quantile` variable
#' and draw horizontal lines at the given quantiles in `geom_violin()`.
#'
#' @eval rd_computed_vars(
Expand All @@ -19,7 +19,7 @@
#' counts or to a constant maximum width.",
#' n = "Number of points.",
#' width = "Width of violin bounding box.",
#' quantile = "Whether the row is part of the `draw_quantiles` computation."
#' quantile = "Whether the row is part of the `quantiles` computation."
#' )
#'
#' @seealso [geom_violin()] for examples, and [stat_density()]
Expand All @@ -29,7 +29,7 @@
stat_ydensity <- function(mapping = NULL, data = NULL,
geom = "violin", position = "dodge",
...,
draw_quantiles = NULL,
quantiles = c(0.25, 0.50, 0.75),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need to properly deprecate draw_quantiles here

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because stat_ydensity(draw_quantiles) never was a formal argument, I've deprecated in the parameter setup rather than constructor.

bw = "nrd0",
adjust = 1,
kernel = "gaussian",
Expand Down Expand Up @@ -60,7 +60,7 @@ stat_ydensity <- function(mapping = NULL, data = NULL,
drop = drop,
na.rm = na.rm,
bounds = bounds,
draw_quantiles = draw_quantiles,
quantiles = quantiles,
...
)
)
Expand All @@ -86,7 +86,7 @@ StatYdensity <- ggproto("StatYdensity", Stat,
compute_group = function(self, data, scales, width = NULL, bw = "nrd0", adjust = 1,
kernel = "gaussian", trim = TRUE, na.rm = FALSE,
drop = TRUE, flipped_aes = FALSE, bounds = c(-Inf, Inf),
draw_quantiles = NULL) {
quantiles = c(0.25, 0.50, 0.75)) {
if (nrow(data) < 2) {
if (isTRUE(drop)) {
cli::cli_warn(c(
Expand Down Expand Up @@ -121,19 +121,19 @@ StatYdensity <- ggproto("StatYdensity", Stat,
}
dens$width <- width

if (!is.null(draw_quantiles)) {
if (!(all(draw_quantiles >= 0) && all(draw_quantiles <= 1))) {
cli::cli_abort("{.arg draw_quantiles} must be between 0 and 1.")
if (!is.null(quantiles)) {
if (!(all(quantiles >= 0) && all(quantiles <= 1))) {
cli::cli_abort("{.arg quantiles} must be between 0 and 1.")
}
if (!is.null(data[["weight"]]) || !all(data[["weight"]] == 1)) {
cli::cli_warn(
"{.arg draw_quantiles} for weighted data is not implemented."
"{.arg quantiles} for weighted data is not implemented."
)
}
quants <- quantile(data$y, probs = draw_quantiles)
quants <- quantile(data$y, probs = quantiles)
quants <- data_frame0(
y = unname(quants),
quantile = draw_quantiles
quantile = quantiles
)

# Interpolate other metrics
Expand All @@ -152,12 +152,12 @@ StatYdensity <- ggproto("StatYdensity", Stat,
compute_panel = function(self, data, scales, width = NULL, bw = "nrd0", adjust = 1,
kernel = "gaussian", trim = TRUE, na.rm = FALSE,
scale = "area", flipped_aes = FALSE, drop = TRUE,
bounds = c(-Inf, Inf), draw_quantiles = NULL) {
bounds = c(-Inf, Inf), quantiles = c(0.25, 0.50, 0.75)) {
data <- flip_data(data, flipped_aes)
data <- ggproto_parent(Stat, self)$compute_panel(
data, scales, width = width, bw = bw, adjust = adjust, kernel = kernel,
trim = trim, na.rm = na.rm, drop = drop, bounds = bounds,
draw_quantiles = draw_quantiles
quantiles = quantiles
)
if (!drop && any(data$n < 2)) {
cli::cli_warn(
Expand Down
18 changes: 15 additions & 3 deletions man/geom_violin.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading