Skip to content

Commit 2f278f1

Browse files
committed
add weight aesthetic
1 parent f468053 commit 2f278f1

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

R/stat-ellipse.R

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ stat_ellipse <- function(mapping = NULL, data = NULL,
7676
#' @export
7777
StatEllipse <- ggproto("StatEllipse", Stat,
7878
required_aes = c("x", "y"),
79+
optional_aes = "weight",
80+
dropped_aes = "weight",
7981

8082
setup_params = function(data, params) {
8183
params$type <- params$type %||% "t"
@@ -96,6 +98,9 @@ calculate_ellipse <- function(data, vars, type, level, segments){
9698
dfn <- 2
9799
dfd <- nrow(data) - 1
98100

101+
weight <- data$weight %||% rep(1, nrow(data))
102+
weight <- weight / sum(weight)
103+
99104
if (!type %in% c("t", "norm", "euclid")) {
100105
cli::cli_inform("Unrecognized ellipse type")
101106
ellipse <- matrix(NA_real_, ncol = 2)
@@ -104,11 +109,12 @@ calculate_ellipse <- function(data, vars, type, level, segments){
104109
ellipse <- matrix(NA_real_, ncol = 2)
105110
} else {
106111
if (type == "t") {
107-
v <- MASS::cov.trob(data[,vars])
112+
# Prone to convergence problems when `sum(weight) != nrow(data)`
113+
v <- MASS::cov.trob(data[,vars], wt = weight * nrow(data))
108114
} else if (type == "norm") {
109-
v <- stats::cov.wt(data[,vars])
115+
v <- stats::cov.wt(data[,vars], wt = weight)
110116
} else if (type == "euclid") {
111-
v <- stats::cov.wt(data[,vars])
117+
v <- stats::cov.wt(data[,vars], wt = weight)
112118
v$cov <- diag(rep(min(diag(v$cov)), 2))
113119
}
114120
shape <- v$cov

0 commit comments

Comments
 (0)