Skip to content

Commit 66d9dee

Browse files
committed
support alpha/fill gradients in geom_ribbon()
1 parent 9f2b8ba commit 66d9dee

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

R/geom-ribbon.R

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,42 @@ GeomRibbon <- ggproto("GeomRibbon", Geom,
135135
data <- data[order(data$group), ]
136136

137137
# Check that aesthetics are constant
138-
aes <- unique0(data[names(data) %in% c("colour", "fill", "linewidth", "linetype", "alpha")])
139-
if (nrow(aes) > 1) {
140-
cli::cli_abort("Aesthetics can not vary along a ribbon.")
138+
aes <- lapply(
139+
data[names(data) %in% c("colour", "fill", "linewidth", "linetype", "alpha")],
140+
unique0
141+
)
142+
non_constant <- names(aes)[lengths(aes) > 1]
143+
if (coord$is_linear()) {
144+
# For linear coords, we can make a fill/alpha gradient, so we allow
145+
# these to vary
146+
non_constant <- setdiff(non_constant, c("fill", "alpha"))
147+
}
148+
if (length(non_constant) > 1) {
149+
cli::cli_abort(
150+
"Aesthetics can not vary along a ribbon: {.field {.and non_constant}}."
151+
)
152+
}
153+
if (length(aes$fill) > 1 || length(aes$alpha) > 1) {
154+
check_device("gradients")
155+
transformed <- coord$transform(flip_data(data, flipped_aes), panel_params)
156+
if (flipped_aes) {
157+
keep <- is.finite(tranformed$y)
158+
args <- list(
159+
colours = alpha(data$fill, data$alpha)[keep],
160+
stops = rescale(transformed$y)[keep],
161+
y1 = 0, y2 = 1, x1 = 0.5, x2 = 0.5
162+
)
163+
} else {
164+
keep <- is.finite(transformed$x)
165+
args <- list(
166+
colours = alpha(data$fill, data$alpha)[keep],
167+
stops = rescale(transformed$x)[keep],
168+
x1 = 0, x2 = 1, y1 = 0.5, y2 = 0.5
169+
)
170+
}
171+
aes$fill <- inject(linearGradient(!!!args))
172+
aes$alpha <- NA
141173
}
142-
aes <- as.list(aes)
143174

144175
# Instead of removing NA values from the data and plotting a single
145176
# polygon, we want to "stop" plotting the polygon whenever we're

0 commit comments

Comments
 (0)