From 8d7100f44e1bb8bb7bf05f176f00e36a50e115be Mon Sep 17 00:00:00 2001 From: Josh <39366189+M-Colley@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:21:44 +0000 Subject: [PATCH] Apply ggplot2 theme palettes during conversion --- NEWS.md | 2 ++ R/ggplotly.R | 3 +++ tests/testthat/test-ggplot-ggplotly.R | 22 ++++++++++++++++++++++ 3 files changed, 27 insertions(+) diff --git a/NEWS.md b/NEWS.md index 6581d724aa..b595a359c0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -7,6 +7,8 @@ ## Bug fixes +* `ggplotly()` now applies palettes supplied by the ggplot2 theme (#2505). + * Closed #2483: `save_image()` no longer embeds Windows file paths directly into Python source passed to `reticulate`, fixing static image export with Kaleido on Windows. * #2495: `ggplotly()` now keeps merged legend titles in sync with their legend entries, fixing a case where an upstream change in `{rlang}`'s hashing could silently reorder combined legend titles (e.g. `factor(vs)
factor(cyl)`) out of step with the entries they label. diff --git a/R/ggplotly.R b/R/ggplotly.R index afe8befbf3..b25ffcbe96 100644 --- a/R/ggplotly.R +++ b/R/ggplotly.R @@ -406,6 +406,9 @@ gg2list <- function(p, width = NULL, height = NULL, # Train and map non-position scales npscales <- scales$non_position_scales() if (npscales$n() > 0) { + if (is.function(npscales$set_palettes)) { + npscales$set_palettes(ggfun("plot_theme")(plot)) + } lapply(data, scales_train_df, scales = npscales) # this for loop is unique to plotly -- it saves the "domain" # of each non-positional scale for display in tooltips diff --git a/tests/testthat/test-ggplot-ggplotly.R b/tests/testthat/test-ggplot-ggplotly.R index 52c8238603..5499bdfc63 100644 --- a/tests/testthat/test-ggplot-ggplotly.R +++ b/tests/testthat/test-ggplot-ggplotly.R @@ -28,3 +28,25 @@ test_that("can access ggplot data in layout()", { l <- ggplotly(p) %>% layout(title = ~range(date)) expect_equivalent(plotly_build(l)$x$layout$title, range(txhousing$date)) }) + +test_that("ggplotly uses the discrete colour palette from the theme", { + skip_if_not_installed("ggplot2", "4.0.0") + + colours <- c("#147D86", "#7A1125") + manual <- c("#2155A3", "#E48023") + points <- data.frame(x = 1:2, y = 1:2, group = c("a", "b")) + plot <- ggplot(points, aes(x, y, colour = group)) + + geom_point() + + theme(palette.colour.discrete = grDevices::colorRampPalette(colours)) + + trace_colours <- function(plot) { + traces <- plotly_build(ggplotly(plot))$x$data + vapply(traces, function(trace) trace$marker$color, character(1)) + } + + expect_identical(trace_colours(plot), toRGB(colours)) + expect_identical( + trace_colours(plot + scale_colour_manual(values = manual)), + toRGB(manual) + ) +})