4
4
# ' @param scale if "area" (default), all violins have the same area (before trimming
5
5
# ' the tails). If "count", areas are scaled proportionally to the number of
6
6
# ' observations. If "width", all violins have the same maximum width.
7
+ # ' @param drop Whether to discard groups with less than 2 observations
8
+ # ' (`TRUE`, default) or keep such groups for position adjustment purposes
9
+ # ' (`FALSE`).
7
10
# ' @section Computed variables:
8
11
# ' \describe{
9
12
# ' \item{density}{density estimate}
@@ -26,6 +29,7 @@ stat_ydensity <- function(mapping = NULL, data = NULL,
26
29
kernel = " gaussian" ,
27
30
trim = TRUE ,
28
31
scale = " area" ,
32
+ drop = TRUE ,
29
33
na.rm = FALSE ,
30
34
orientation = NA ,
31
35
show.legend = NA ,
@@ -46,6 +50,7 @@ stat_ydensity <- function(mapping = NULL, data = NULL,
46
50
kernel = kernel ,
47
51
trim = trim ,
48
52
scale = scale ,
53
+ drop = drop ,
49
54
na.rm = na.rm ,
50
55
...
51
56
)
@@ -70,8 +75,18 @@ StatYdensity <- ggproto("StatYdensity", Stat,
70
75
extra_params = c(" na.rm" , " orientation" ),
71
76
72
77
compute_group = function (self , data , scales , width = NULL , bw = " nrd0" , adjust = 1 ,
73
- kernel = " gaussian" , trim = TRUE , na.rm = FALSE , flipped_aes = FALSE ) {
78
+ kernel = " gaussian" , trim = TRUE , na.rm = FALSE ,
79
+ drop = TRUE , flipped_aes = FALSE ) {
74
80
if (nrow(data ) < 2 ) {
81
+ if (isTRUE(drop )) {
82
+ cli :: cli_warn(c(
83
+ " Groups with fewer than two datapoints have been dropped." ,
84
+ i = paste0(
85
+ " Set {.code drop = FALSE} to consider such groups for position " ,
86
+ " adjustment purposes."
87
+ )))
88
+ return (data_frame0())
89
+ }
75
90
ans <- data_frame0(x = data $ x , n = nrow(data ))
76
91
return (ans )
77
92
}
@@ -95,15 +110,15 @@ StatYdensity <- ggproto("StatYdensity", Stat,
95
110
96
111
compute_panel = function (self , data , scales , width = NULL , bw = " nrd0" , adjust = 1 ,
97
112
kernel = " gaussian" , trim = TRUE , na.rm = FALSE ,
98
- scale = " area" , flipped_aes = FALSE ) {
113
+ scale = " area" , flipped_aes = FALSE , drop = TRUE ) {
99
114
data <- flip_data(data , flipped_aes )
100
115
data <- ggproto_parent(Stat , self )$ compute_panel(
101
116
data , scales , width = width , bw = bw , adjust = adjust , kernel = kernel ,
102
- trim = trim , na.rm = na.rm
117
+ trim = trim , na.rm = na.rm , drop = drop
103
118
)
104
- if (any(data $ n < 2 )) {
119
+ if (! drop && any(data $ n < 2 )) {
105
120
cli :: cli_warn(
106
- " Cannot compute density for groups with fewer than two data points ."
121
+ " Cannot compute density for groups with fewer than two datapoints ."
107
122
)
108
123
}
109
124
0 commit comments