Skip to content

Commit 19d9b2e

Browse files
committed
Don't drop groups in stat_ydensity
1 parent ef00be7 commit 19d9b2e

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

R/stat-ydensity.r

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,8 @@ StatYdensity <- ggproto("StatYdensity", Stat,
7272
compute_group = function(self, data, scales, width = NULL, bw = "nrd0", adjust = 1,
7373
kernel = "gaussian", trim = TRUE, na.rm = FALSE, flipped_aes = FALSE) {
7474
if (nrow(data) < 2) {
75-
cli::cli_warn("Groups with fewer than two data points have been dropped.")
76-
return(data_frame0())
75+
ans <- data_frame0(x = data$x, n = nrow(data))
76+
return(ans)
7777
}
7878
range <- range(data$y, na.rm = TRUE)
7979
modifier <- if (trim) 0 else 3
@@ -101,15 +101,21 @@ StatYdensity <- ggproto("StatYdensity", Stat,
101101
data, scales, width = width, bw = bw, adjust = adjust, kernel = kernel,
102102
trim = trim, na.rm = na.rm
103103
)
104+
if (any(data$n < 2)) {
105+
cli::cli_warn(
106+
"Cannot compute density for groups with fewer than two data points."
107+
)
108+
}
104109

105110
# choose how violins are scaled relative to each other
106111
data$violinwidth <- switch(scale,
107112
# area : keep the original densities but scale them to a max width of 1
108113
# for plotting purposes only
109-
area = data$density / max(data$density),
114+
area = data$density / max(data$density, na.rm = TRUE),
110115
# count: use the original densities scaled to a maximum of 1 (as above)
111116
# and then scale them according to the number of observations
112-
count = data$density / max(data$density) * data$n / max(data$n),
117+
count = data$density / max(data$density, na.rm = TRUE) *
118+
data$n / max(data$n),
113119
# width: constant width (density scaled to a maximum of 1)
114120
width = data$scaled
115121
)

0 commit comments

Comments
 (0)