diff --git a/R/layers2traces.R b/R/layers2traces.R index 181ef72909..d8b91085d7 100644 --- a/R/layers2traces.R +++ b/R/layers2traces.R @@ -62,8 +62,17 @@ layers2traces <- function(data, prestats_data, layout, p) { if ("hovertext" %in% names(x)) x$hovertext <- paste0(x$hovertext, br()) # text aestheic should be taken verbatim (for custom tooltips) prefix <- if (identical(aesName, "text")) "" else paste0(varName, ": ") - # look for the domain, if that's not found, provide the range (useful for identity scales) - txt <- x[[paste0(aesName, "_plotlyDomain")]] %||% x[[aesName]] + txt <- x[[paste0(aesName, "_plotlyDomain")]] + if (is.null(txt)) { + txt <- x[[aesName]] + # Statistics can leave only the transformed temporal coordinates. + if (aesName %in% c("x", "y") && is.numeric(txt)) { + scale <- p$scales$get_scales(aesName) + if (inherits(scale, c("ScaleContinuousDate", "ScaleContinuousDatetime"))) { + txt <- scale$trans$inverse(txt) + } + } + } suffix <- tryNULL(format(txt, justify = "none")) %||% "" # put the height of the bar in the tooltip if (inherits(x, "GeomBar") && identical(aesName, "y")) { diff --git a/tests/testthat/test-ggplot-date.R b/tests/testthat/test-ggplot-date.R index 2bd7704b17..58527e5787 100644 --- a/tests/testthat/test-ggplot-date.R +++ b/tests/testthat/test-ggplot-date.R @@ -38,3 +38,37 @@ test_that("scale_x_date and irregular time series work", { info <- expect_warning(expect_doppelganger_built(dt, "date-irregular-time-series"), regexp = "Aspect ratios aren't yet implemented") }) + +test_that("smooth tooltips display dates", { + dates <- seq(as.Date("1967-07-01"), by = "day", length.out = 10) + df <- data.frame(date = dates, value = (1:10)^2) + gg <- ggplot(df, aes(date, value)) + + geom_point() + + geom_smooth(method = "lm", formula = y ~ x, se = FALSE) + + traces <- plotly_build(ggplotly(gg, tooltip = "x"))$x$data + + expect_identical(as.character(traces[[1]]$text), paste0("date: ", dates)) + expect_identical( + as.character(traces[[2]]$text[c(1, length(traces[[2]]$text))]), + paste0("date: ", dates[c(1, 10)]) + ) + expect_equal(range(traces[[2]]$x), range(as.numeric(dates))) +}) + +test_that("smooth tooltips display datetimes in the scale timezone", { + times <- as.POSIXct("2024-08-05 13:20:00", tz = "America/New_York") + + 3600 * (0:9) + df <- data.frame(time = times, value = (1:10)^2) + gg <- ggplot(df, aes(time, value)) + + geom_smooth(method = "lm", formula = y ~ x, se = FALSE) + + scale_x_datetime(timezone = "America/New_York") + + traces <- plotly_build(ggplotly(gg, tooltip = "x"))$x$data + + expect_identical( + as.character(traces[[1]]$text[c(1, length(traces[[1]]$text))]), + paste0("time: ", format(times[c(1, 10)])) + ) + expect_equal(range(traces[[1]]$x), range(as.numeric(times))) +})