Skip to content

Commit a641f5d

Browse files
laurabriannathomasp85teunbrand
authored
Fixes #3533 - Swap date(time) types in opposite scale (#6042)
* Fixes #3533 - helpful error msg on date vs datetime scale * Apply suggestions from code review Co-authored-by: Thomas Lin Pedersen <[email protected]> * Apply suggestions from code review Co-authored-by: Thomas Lin Pedersen <[email protected]> * add news bullet * add test * use internal data.frame --------- Co-authored-by: Thomas Lin Pedersen <[email protected]> Co-authored-by: Teun van den Brand <[email protected]>
1 parent 1800a9a commit a641f5d

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# ggplot2 (development version)
22

3+
* Date scales silently coerce <POSIXct> to <Date> and datetime scales silently
4+
coerce <Date> to <POSIXct> (@laurabrianna, #3533)
35
* New parameters for `geom_label()` (@teunbrand and @steveharoz, #5365):
46
* The `linewidth` aesthetic is now applied and replaces the `label.size`
57
argument.

R/scale-date.R

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,9 @@ ScaleContinuousDatetime <- ggproto("ScaleContinuousDatetime", ScaleContinuous,
394394
i = "The value was converted to {obj_type_friendly(x)}."
395395
), call = self$call)
396396
}
397+
if (inherits(x, "Date")) {
398+
x <- as.POSIXct(x)
399+
}
397400
ggproto_parent(ScaleContinuous, self)$transform(x)
398401
},
399402
map = function(self, x, limits = self$get_limits()) {
@@ -441,6 +444,9 @@ ScaleContinuousDate <- ggproto("ScaleContinuousDate", ScaleContinuous,
441444
i = "The value was converted to {obj_type_friendly(x)}."
442445
), call = self$call)
443446
}
447+
if (inherits(x, "POSIXct")) {
448+
x <- as.Date(x)
449+
}
444450
ggproto_parent(ScaleContinuous, self)$transform(x)
445451
},
446452
get_breaks = function(self, limits = self$get_limits()) {

tests/testthat/test-scale_date.R

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,19 @@
11

2+
test_that("date(time) scales coerce data types", {
3+
4+
date <- as.Date("2024-11-11")
5+
datetime <- as.POSIXct(date)
6+
7+
sc <- scale_x_datetime()
8+
df <- sc$transform_df(data_frame0(x = date))
9+
expect_equal(df$x, as.numeric(datetime))
10+
11+
sc <- scale_x_date()
12+
df <- sc$transform_df(data_frame0(x = datetime))
13+
expect_equal(df$x, as.numeric(date))
14+
15+
})
16+
217
# Visual tests ------------------------------------------------------------
318

419
test_that("date scale draws correctly", {

0 commit comments

Comments
 (0)