Skip to content
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# ggplot2 (development version)

* Date scales silently coerce <POSIXct> to <Date> and datetime scales silently
coerce <Date> to <POSIXct> (@laurabrianna, #3533)
* New parameters for `geom_label()` (@teunbrand and @steveharoz, #5365):
* The `linewidth` aesthetic is now applied and replaces the `label.size`
argument.
Expand Down
6 changes: 6 additions & 0 deletions R/scale-date.R
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down Expand Up @@ -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()) {
Expand Down
15 changes: 15 additions & 0 deletions tests/testthat/test-scale_date.R
Original file line number Diff line number Diff line change
@@ -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", {
Expand Down