Skip to content

Commit 8d7100f

Browse files
committed
Apply ggplot2 theme palettes during conversion
1 parent 4ff1c33 commit 8d7100f

3 files changed

Lines changed: 27 additions & 0 deletions

File tree

‎NEWS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77

88
## Bug fixes
99

10+
* `ggplotly()` now applies palettes supplied by the ggplot2 theme (#2505).
11+
1012
* 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.
1113

1214
* #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)<br />factor(cyl)`) out of step with the entries they label.

‎R/ggplotly.R‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,9 @@ gg2list <- function(p, width = NULL, height = NULL,
406406
# Train and map non-position scales
407407
npscales <- scales$non_position_scales()
408408
if (npscales$n() > 0) {
409+
if (is.function(npscales$set_palettes)) {
410+
npscales$set_palettes(ggfun("plot_theme")(plot))
411+
}
409412
lapply(data, scales_train_df, scales = npscales)
410413
# this for loop is unique to plotly -- it saves the "domain"
411414
# of each non-positional scale for display in tooltips

‎tests/testthat/test-ggplot-ggplotly.R‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,25 @@ test_that("can access ggplot data in layout()", {
2828
l <- ggplotly(p) %>% layout(title = ~range(date))
2929
expect_equivalent(plotly_build(l)$x$layout$title, range(txhousing$date))
3030
})
31+
32+
test_that("ggplotly uses the discrete colour palette from the theme", {
33+
skip_if_not_installed("ggplot2", "4.0.0")
34+
35+
colours <- c("#147D86", "#7A1125")
36+
manual <- c("#2155A3", "#E48023")
37+
points <- data.frame(x = 1:2, y = 1:2, group = c("a", "b"))
38+
plot <- ggplot(points, aes(x, y, colour = group)) +
39+
geom_point() +
40+
theme(palette.colour.discrete = grDevices::colorRampPalette(colours))
41+
42+
trace_colours <- function(plot) {
43+
traces <- plotly_build(ggplotly(plot))$x$data
44+
vapply(traces, function(trace) trace$marker$color, character(1))
45+
}
46+
47+
expect_identical(trace_colours(plot), toRGB(colours))
48+
expect_identical(
49+
trace_colours(plot + scale_colour_manual(values = manual)),
50+
toRGB(manual)
51+
)
52+
})

0 commit comments

Comments
 (0)