diff --git a/NEWS.md b/NEWS.md index ef806483df..67d35b9878 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # ggplot2 (development version) +* Date scales silently coerce to and datetime scales silently + coerce to (@laurabrianna, #3533) * New parameters for `geom_label()` (@teunbrand and @steveharoz, #5365): * The `linewidth` aesthetic is now applied and replaces the `label.size` argument. diff --git a/R/scale-date.R b/R/scale-date.R index e518c7ac11..ac0c314e18 100644 --- a/R/scale-date.R +++ b/R/scale-date.R @@ -394,6 +394,9 @@ ScaleContinuousDatetime <- ggproto("ScaleContinuousDatetime", ScaleContinuous, i = "The value was converted to {obj_type_friendly(x)}." ), call = self$call) } + if (inherits(x, "Date")) { + x <- as.POSIXct(x) + } ggproto_parent(ScaleContinuous, self)$transform(x) }, map = function(self, x, limits = self$get_limits()) { @@ -441,6 +444,9 @@ ScaleContinuousDate <- ggproto("ScaleContinuousDate", ScaleContinuous, i = "The value was converted to {obj_type_friendly(x)}." ), call = self$call) } + if (inherits(x, "POSIXct")) { + x <- as.Date(x) + } ggproto_parent(ScaleContinuous, self)$transform(x) }, get_breaks = function(self, limits = self$get_limits()) { diff --git a/tests/testthat/test-scale_date.R b/tests/testthat/test-scale_date.R index f12a35716c..b9a788bb70 100644 --- a/tests/testthat/test-scale_date.R +++ b/tests/testthat/test-scale_date.R @@ -1,4 +1,19 @@ +test_that("date(time) scales coerce data types", { + + date <- as.Date("2024-11-11") + datetime <- as.POSIXct(date) + + sc <- scale_x_datetime() + df <- sc$transform_df(data_frame0(x = date)) + expect_equal(df$x, as.numeric(datetime)) + + sc <- scale_x_date() + df <- sc$transform_df(data_frame0(x = datetime)) + expect_equal(df$x, as.numeric(date)) + +}) + # Visual tests ------------------------------------------------------------ test_that("date scale draws correctly", {