Skip to content

Commit 3c3917a

Browse files
committed
legend title annotation
1 parent 606d996 commit 3c3917a

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

.Rbuildignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,4 @@
55
CONDUCT.md
66
CONTRIBUTING.md
77
build_site.R
8+
inst/examples/flexdashboard

R/ggplotly.R

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -525,6 +525,23 @@ gg2list <- function(p, width = NULL, height = NULL, tooltip = "all", source = "A
525525
}
526526
}
527527
traces <- c(traces, colorbar)
528+
529+
# legend title annotation - https://github.com/plotly/plotly.js/issues/276
530+
legendTitles <- compact(lapply(gdefs, function(g) if (inherits(g, "legend")) g$title else NULL))
531+
legendTitle <- paste(legendTitles, collapse = "<br>")
532+
titleAnnotation <- make_label(
533+
legendTitle,
534+
x = gglayout$legend$x %||% 1.02,
535+
y = gglayout$legend$y %||% 1,
536+
theme$legend.title,
537+
xanchor = "left",
538+
yanchor = "top"
539+
)
540+
gglayout$annotations <- c(gglayout$annotations, titleAnnotation)
541+
# adjust the height of the legend to accomodate for the title
542+
# this assumes the legend always appears below colorbars
543+
gglayout$legend$y <- (gglayout$legend$y %||% 1) -
544+
length(legendTitles) * unitConvert(theme$legend.title$size, "npc", "height")
528545
}
529546

530547
# geom_bar() hacks

tests/testthat/test-ggplot-legend.R

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ test_that("Discrete colour and shape get merged into one legend", {
2929
expect_identical(
3030
nms, paste0("(", d$vs, ",", d$cyl, ")")
3131
)
32+
a <- info$layout$annotations
33+
expect_match(a[[3]]$text, "^factor\\(vs\\)")
34+
expect_match(a[[3]]$text, "factor\\(cyl\\)$")
35+
expect_true(a[[3]]$y > info$layout$legend$y)
3236
})
3337

3438

0 commit comments

Comments
 (0)